var firstload = true, firstViewport;
var page = 0;
var state = 0; //1.stream_list 2.viewport 3.main_menu 4.load_more_searchInStream 5.stream_detail 6.load_more_thread
var curState;
var curScroll = 0;
var reload = false;
var dateFrom = format(new Date());
var dateTo = format(new Date());
var sentiment = 0; //all sentiments
var language = '2'; //all languages
var type = '0'; // all platforms 
var tag = '0'; // all tags
var messageActionFilter = ''; //favorite archive spam chart
var source = '0'; //all source
var streamId;
var index;
var StreamReq;
var selector;
var temp;
var curRequest, curRequests = [];
var streamSources = new Array();
var currentFolderId, curFolderName, curParentId, currentTagGroupId, curGroupName, tagKeywords = new Array();
var width;

var main_menu = document.getElementById("main-menu");
var viewport = document.getElementById("action-menu-content");
var controller = document.getElementById("controller-container");

document.addEventListener("DOMContentLoaded", function() {
    if (firstload)
    {
        params = window.location.href.split("#");
        if (params.length > 1) {
            navigateURL(params[1]);
        }else{
            addEventMainMenu();
            addEventMainAction();
            removeClass(document.getElementById('content'), 'hide');
            removeClass(document.getElementById('header'), 'hide');
        }
        firstload = false;
    }
});

window.onhashchange = function(data) {
    params = window.location.href.split("#");
    if (params.length > 0) {
        navigateURL(params[1]);
        removeClass(viewport, "show");
        removeClass(main_menu, "show");
        controller.style.height = 'auto';
        if(StreamReq !== null && StreamReq !== undefined){
            StreamReq.abort();
        }
    }
};

function navigateURL(param) {
    params = param.split('/');
    if (window.location.href.split('#')[1] !== undefined)
        if (window.location.href.split('#')[1].toLowerCase() !== param.toLowerCase())
            history.pushState({page: 1}, param, "#" + param);
    loadViewPort(params);
    loadMainView(params);
}

function loadViewPort(params) {
    switch (params[0]) {
        case "home":
            break;
        case "activity":
            sendRequest("activity/viewport", activity_viewport, process);
            streamId = params[1];
            if(params[1] === "manager") {
                document.getElementById('header').getElementsByClassName('title')[0].textContent = "TASK MANAGER";
            } else {
                document.getElementById('header').getElementsByClassName('title')[0].textContent = "MY TASKS";
            }
            break;
        case "stream":
            sendRequest("stream/" + params[1] + "/viewport", stream_viewport, process);
            streamId = params[1];
            break;
        case "settings":
            sendRequest("settings/" + params[1] + "/viewport", settings_viewport, process);
            break;
        case "metrics":
            sendRequest("metrics/" + params[1] + "/viewport", metrics_viewport, process);
            streamId = params[1];
            break;
        case "engagement":
            sendRequest("engagement/" + params[1] + "/viewport", engagement_viewport, process);
            streamId = params[1];
            break;
        case "compare":
            streamId = params[1];
            if(firstload){
                firstViewport = true;
                sendRequest("compare/" + params[1] + "/viewport", compare_viewport, process);
            }
            break;
        case "alert":
            break;
    }
}

function loadMainView(params) {
    switch (params[0]) {
        case "":
        case "home":
            sendRequest("home/mainview", home_mainview, process);
            break;
        case "activity":
            addClass(document.getElementById('content'), 'hide');
            removeClass(document.getElementById('loading'), 'hide');
            removeClass(document.getElementById("filter-button"), "selected");
            if(params[1] !== undefined) {
                sendRequest("activity/" + params[1] + "/mainview", activity_mainview, process);
            } else {
                sendRequest("activity/mainview", activity_mainview, process);
            }
            break;
        case "stream":
            sendRequest("stream/" + params[1] + "/mainview", stream_mainview, process);
            break;
        case "settings":
            sendRequest("settings/" + params[1] + "/mainview", settings_mainview, process);
            break;
        case "metrics":
            sendRequest("metrics/" + params[1] + "/mainview", metrics_mainview, process);
            break;
        case "engagement":
            break;
        case "compare":
            if(!firstload){
                sendRequest("compare/" + params[1] + "/mainview", compare_mainview, process);
            }
            break;
        case "alert":
            sendRequest("alert/" + params[1] + "/mainview", alert_mainview, process);
            break;
    }
}
//support function
function addClass(el, className) {
    if(el !== null && el !== undefined){
        removeClass(el, className);
        el.className += ' ' + className;
    }
}

function removeClass(el, className) {
    if(el !== null && el !== undefined){
        var elClass = ' ' + el.className;
        while (elClass.indexOf(' ' + className) !== - 1)
            elClass = elClass.replace(' ' + className, '');
        el.className = elClass.substr(1, elClass.length - 1);
    }
}

function expand(element) {
    addClass(element.previousSibling.previousSibling, 'hide');
    addClass(element, 'hide');
    removeClass(element.nextSibling.nextSibling, 'hide');
    removeClass(element.nextSibling.nextSibling.nextSibling.nextSibling, 'hide');
}

function unexpand(element) {
    addClass(element.previousSibling.previousSibling, 'hide');
    addClass(element, 'hide');
    removeClass(element.previousSibling.previousSibling.previousSibling.previousSibling, 'hide');
    removeClass(element.previousSibling.previousSibling.previousSibling.previousSibling.previousSibling.previousSibling, 'hide');
}

var exec_body_scripts = function(body_el) {
  // Finds and executes scripts in a newly added element's body.
  // Needed since innerHTML does not run scripts.
  //
  // Argument body_el is an element in the dom.
  
  function nodeName(elem, name) {
    return elem.nodeName && elem.nodeName.toUpperCase() ===
              name.toUpperCase();
  };

  function evalScript(elem) {
    var data = (elem.text || elem.textContent || elem.innerHTML || "" ),
        head = document.getElementsByTagName("head")[0] ||
                  document.documentElement,
        script = document.createElement("script");

    script.type = "text/javascript";
    try {
      // doesn't work on ie...
      script.appendChild(document.createTextNode(data));      
    } catch(e) {
      // IE has funky script nodes
      script.text = data;
    }
    head.appendChild(script);
    head.insertBefore(script, head.firstChild);
    head.removeChild(script);
  };

  // main section of function
  var scripts = [],
      script,
      children_nodes = body_el.childNodes,
      child,
      i;

  for (i = 0; children_nodes[i]; i++) {
    child = children_nodes[i];
    if (nodeName(child, "script" ) &&
      (!child.type || child.type.toLowerCase() === "text/javascript")) {
          scripts.push(child);
      }
  }

  for (i = 0; scripts[i]; i++) {
    script = scripts[i];
    if (script.parentNode) {script.parentNode.removeChild(script);}
    evalScript(scripts[i]);
  }
};

function loadScript(urls, callback){
    for(var i = 0; i < urls.length; i++){
        // Adding the script tag to the head as suggested before
        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = urls[i];

        if(i === urls.length - 1){
            // Then bind the event to the callback function.
            // There are several events for cross browser compatibility.
            script.onreadystatechange = callback;
            script.onload = callback;
        }

        // Fire the loading
        head.appendChild(script);
    }
}

var home_mainview = function(data) {
    controller.innerHTML = data;
    state = 7;
    document.getElementById('content').style.background = '#E5E5E5';
    removeClass(document.getElementById('content'), 'hide');
    removeClass(document.getElementById('header'), 'hide');
    addEventMainMenu();
    addEventMainAction();
};
document.getElementById('content').style.background = '#E5E5E5';

function addEventMainAction(){
    eventAddStream();
    document.getElementById('home-button').addEventListener('click', function(){
        if(document.getElementById('content-addstream') !== null){
            removeClass(document.getElementById('content-home'), 'hide');
            addClass(document.getElementById('content-addstream'), 'hide');
            document.getElementById('header').getElementsByClassName('title')[0].innerHTML = '<img src="Images/logo-beta.png" alt="">';
            eventAddStream();
            //reset
            removeClass(document.getElementById('basic-div'), 'hide');
            addClass(document.getElementById('advance-div'), 'hide');
            removeClass(document.getElementById('advance-query'), 'select');
            addClass(document.getElementById('basic-query'), 'select');          
        }
    }, false);
}

function eventAddStream(){
    document.getElementById('add-stream').addEventListener('click', function(){
        sendRequest("ajax/addStream", addStream_callback, addStream_process);
    }, false);
}

function addStream_process(){
    removeClass(document.getElementsByClassName("loading")[0], 'hide');
    addClass(document.getElementById("content"), 'hide');
}

function addStream_callback(data){
    addClass(document.getElementsByClassName("loading")[0], 'hide');
    removeClass(document.getElementById("content"), 'hide');
    //change content home to content addstream
    document.getElementById('header').getElementsByClassName('title')[0].innerHTML = 'Add Stream';
    addClass(document.getElementById('content-home'), 'hide');
    document.getElementById('content').innerHTML += data;
    
    document.getElementById('basic-query').addEventListener('click',function() {
        removeClass(document.getElementById('basic-div'), 'hide');
        addClass(document.getElementById('advance-div'), 'hide');
        addClass(this, 'select');
        if(window.hasClass(document.getElementById('advance-query'), 'select')){
            removeClass(document.getElementById('advance-query'), 'select');
            document.getElementById('query-all').value = "";
            document.getElementById('query-any').value = "";
            document.getElementById('query-none').value = "";
        }
    }, false);

    document.getElementById('advance-query').addEventListener('click', function() {
        addClass(document.getElementById('basic-div'), 'hide');
        removeClass(document.getElementById('advance-div'), 'hide');
        removeClass(document.getElementById('basic-query'), 'select');
        addClass(this, 'select');
        //change query style
        var query = new Array();
        query['all'] = document.getElementById('query-all').value;
        query['any'] = document.getElementById('query-any').value;
        query['none'] = document.getElementById('query-none').value;
        document.getElementById('query-adv').value = createQuery(query);
    }, false);
    
    //expand tag-bar
    document.getElementById('source-bar').getElementsByClassName('source-zone')[0].getElementsByClassName('threedot')[0].addEventListener('click', function(){
        if(!window.hasClass(this.parentElement, 'expanded')){
            addClass(this.parentElement, 'expanded');
        }
        else{
            removeClass(this.parentElement, 'expanded');
        }
    }, false);
    
    document.getElementById('addsource-button').addEventListener('click', function(){
        var input = this.parentElement.getElementsByClassName('url-source')[0];
        var expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
        var regex = new RegExp(expression);
        if(input.value.match(regex) && streamSources.indexOf(input.value) === -1){
            var source_bar = document.getElementById('source-bar');
            var source_zone = source_bar.getElementsByClassName('source-zone')[0];
            var sources = source_bar.getElementsByClassName('source');

            //create sourceNode
            var source = document.createElement('div');
            source.setAttribute('class', 'source new');
            var namediv = document.createElement('div');
            namediv.setAttribute('class', 'name');
            namediv.textContent = input.value;
            source.appendChild(namediv);
            var del = document.createElement('div');
            del.setAttribute('class', 'del');
            del.textContent = 'x';
            source.appendChild(del);

            //delete event of Tag
            source.getElementsByTagName('div')[1].addEventListener('click', function(){
                source.parentNode.removeChild(source);
                remove_item(streamSources, source.getElementsByClassName('name')[0].textContent);
                sources = source_bar.getElementsByClassName('source');
                var sources_width = 0;
                for(var i = 0; i < sources.length; i++){
                    sources_width += sources[i].clientWidth + 5;
                }
                if(sources_width + 32 <= source_zone.clientWidth) {
                    addClass(source_zone.getElementsByClassName('threedot')[0], 'hide');
                    removeClass(source_zone, 'expanded');
                }
                if(sources.length < 2){
                    addClass(source_bar, 'hide');
                }
            }, false);

            //show tag-bar
            if(window.hasClass(source_bar, 'hide')){
                removeClass(source_bar, 'hide');
            }

            //add Tag
            source_zone.appendChild(source);
            streamSources.push(input.value);

            //show expanded
            var sources_width = 0;
            for(var i = 0; i < sources.length; i++){
                sources_width += sources[i].clientWidth + 5;
            }
            if(sources_width + 32 > source_zone.clientWidth){
                removeClass(source_zone.getElementsByClassName('threedot')[0], 'hide');
            }
            removeClass(source_zone.getElementsByClassName('new')[0], 'new');
            
            //clear input
            input.value = "";
        }
    }, false);
    
    document.getElementById('savestream-button').addEventListener('click', function(){
        var streamid = "";
        var name = document.getElementById('stream-name').value;
        var type = 1;
        var streamQuery = "";
        if (!window.hasClass(document.getElementById('advance-div'), 'hide')){
            streamQuery = '\t' + document.getElementById('advance-query');
        }else{
            var query = new Array();
            query['all'] = document.getElementById('query-all').value;
            query['any'] = document.getElementById('query-any').value;
            query['none'] = document.getElementById('query-none').value;
            streamQuery = createQuery(query);
        }
        var language = document.getElementById('language-addstream').value;
        var location = document.getElementById('location-addstream').value;
        var platform = document.getElementById('platform-addstream').value;
        var externalSources = streamSources.join(';');
        var folderid = document.getElementById('folderid').value;
        var pl = new SOAPClientParameters();
        pl.add("typedata", "stream");
        pl.add('streamId', streamid);
        pl.add("userId", currentUserId);
        pl.add("name", name);
        pl.add('type', type);
        pl.add('query', streamQuery);
        pl.add('language', language);
        pl.add('location', location);
        pl.add('platform', platform);
        pl.add('externalSources', externalSources);
        pl.add('folderId', folderid);
        SOAPClient.invoke("/m/", "saveStream", pl, true, addStreamCompleted);
    }, false);
}

function addStreamCompleted(r){
    if(r['streamId'] !== "undefined"){
        window.location = '/#stream/' + Base64.encode(r['streamId']);
    }
}

var activity_viewport = function(data){
    viewport.innerHTML = data;
    
    //highlight option of settings menu
    var options = viewport.getElementsByTagName('li');
    for(var i = 0; i < options.length; i++){
        if(params[1] === undefined && options[i].attributes['data-type'] !== undefined && options[i].attributes['data-type'].value === 'tasks'){
            removeClass(viewport.getElementsByClassName('selected')[0], 'selected');
            addClass(options[i], 'selected');
        } else if(options[i].attributes['data-type'] !== undefined && options[i].attributes['data-type'].value === params[1]){
            removeClass(viewport.getElementsByClassName('selected')[0], 'selected');
            addClass(options[i], 'selected');
        }
    }
};

var activity_mainview = function(data){
    controller.innerHTML = data;
    removeClass(document.getElementById('content'), 'hide');
    addClass(document.getElementById('loading'), 'hide');
    addEventTopBanner();
    if(params[1] === "manager") { 
        exec_body_scripts(controller);
        eventManagerView();
    } else {
        addEventTaskHead();
        eventTaskOptionBar();
    }
};

function eventManagerView() {
    //isdone button of task
    var buttons = document.getElementsByClassName('isdone');
    for (var i = 0; i < buttons.length; i++) {
        buttons[i].getElementsByTagName('i')[0].addEventListener('click', function(){
            var type = this.attributes['datatype'].value;
            //show form by type if not yet complete action
            if(!window.hasClass(this, 'complete')) {
                removeClass(document.getElementById(type), 'hide');
                addClass(this.parentElement.parentElement, 'selected');
            }
        }, false);
    }
    
    //cancel-button of forms
    var cancel_button = document.getElementById('header').getElementsByClassName('cancel');
    for(var i = 0; i < cancel_button.length; i++){
        cancel_button[i].addEventListener('click', function(){
            addClass(this.parentElement.parentElement.parentElement, 'hide');
            var selected_task = document.getElementById('taskList').getElementsByClassName('task selected')[0];
            removeClass(selected_task, 'selected');
            //reset
            switch(this.attributes['dataType'].value){
                case "send-email":
                    break;
                case 'send-sms':
                    var sendSMS_form = document.getElementById('send-sms');
                    sendSMS_form.getElementsByTagName('input')[0].value = '';
                    sendSMS_form.getElementsByTagName('textarea')[0].value = '';
                    break;
                case 'mark-complete':
                    var completeTask_form = document.getElementById('mark-complete');
                    completeTask_form.getElementsByTagName('textarea')[0].value = '';
                    break;
            }
        }, false);
    }
    
    //submit-button of forms
    var submit_button = document.getElementById('header').getElementsByClassName('submit');
    for(var i = 0; i < submit_button.length; i++){
        submit_button[i].addEventListener('click', function(){
            var type = this.attributes['dataType'].value;
            var selected_task = document.getElementById('taskList').getElementsByClassName('task selected')[0];
            var pl = new SOAPClientParameters();
            switch(type){
                case "send-email":
                    break;
                case 'send-sms':
                    var alert = document.getElementById(type).getElementsByTagName('p')[1];
                    var sendTo = this.parentElement.getElementsByTagName('input')[0].value;
                    var message = this.parentElement.getElementsByTagName('textarea')[0].value;
                    if(sendTo !== '' && message !== ''){
                        pl.add("phoneNumber", sendTo);
                        pl.add("message", message);
                        alert.style.display = 'none';
                        SOAPClient.invoke("/m/", "sendSMS", pl, true, function(r) {
                            var timeout = setTimeout(function() {
                                alert.style.display = '';
                            }, 500);
                        });
                        
                        //reset
                        addClass(document.getElementById(type), 'hide');
                        this.parentElement.getElementsByTagName('input')[0].value = '';
                        this.parentElement.getElementsByTagName('textarea')[0].value = '';
                    }
                    break;
                case 'mark-complete':
                    var curTaskId = selected_task.attributes['taskid'].value;
                    var taskAction = document.getElementById('mark-complete').getElementsByTagName('textarea')[0].value;
                    pl = new SOAPClientParameters();
                    pl.add("id", curTaskId);
                    pl.add("action", taskAction);
                    SOAPClient.invoke("/m", "markComplete", pl, true, function(r){
                        var selected_task = document.getElementById('taskList').getElementsByClassName('task selected')[0];
                        addClass(selected_task.getElementsByClassName('isdone')[0].getElementsByTagName('i')[0], 'complete');
                        removeClass(selected_task, 'selected');
                    });
                    
                    //reset
                    addClass(document.getElementById(type), 'hide');
                    this.parentElement.getElementsByTagName('textarea')[0].value = '';
                    break;
            }
        }, false);
    }
}

function addEventTaskHead(){
    var tasks = document.getElementById('task-list').getElementsByClassName('mention-head');
    for(var i = 0; i < tasks.length; i++){
        tasks[i].addEventListener('click', function(){
            if(!window.hasClass(this, 'selected')){
                //close all mention-head and only show one
                for(var j = 0; j < tasks.length; j++){
                    addClass(tasks[j].parentElement, 'hide');
                }
                //effects of show
                addClass(document.getElementById('content'), 'hide');
                removeClass(document.getElementById('loading'), 'hide');
                selector = this;
                setTimeout(function(){
                    removeClass(document.getElementById('content'), 'hide');
                    addClass(document.getElementById('loading'), 'hide');
                    setTimeout(function(){
                        selector.style.borderLeftColor = '#fff';
                    }, 1000);
                }, 200);
                addClass(this, 'selected');
                removeClass(this.parentElement, 'hide');
                removeClass(this.parentElement.getElementsByClassName('buzz-task')[0], 'hide');
                document.getElementById('task-list').style.marginTop = '90px';
                document.getElementById('option').style.marginTop = '50px';

                //settings tag_bar
                var tag_bar = this.getElementsByClassName('tag-bar')[0];
                var tag_zone = tag_bar.getElementsByClassName('tag-zone')[0];
                var tags = tag_bar.getElementsByClassName('tag');
                if(tags.length > 1){
                    removeClass(tag_bar, 'hide');
                    var tags_width = 0;
                    for(var i = 0; i < tags.length; i++){
                        tags_width += tags[i].clientWidth + 5;
                    }
                    if(tags_width + 32 > tag_zone.clientWidth){
                        removeClass(tag_zone.getElementsByClassName('threedot')[0], 'hide');
                    }
                }

                //expand tag-bar
                this.getElementsByClassName('tag-zone')[0].getElementsByClassName('threedot')[0].addEventListener('click', function(){
                    if(!window.hasClass(this.parentElement, 'expanded')){
                        addClass(this.parentElement, 'expanded');
                    }
                    else{
                        removeClass(this.parentElement, 'expanded');
                    }
                }, false);
                
                //event mark-complete button
                this.parentElement.getElementsByClassName('mark-complete')[0].addEventListener('click', function(){
                    if(!window.hasClass(this.parentElement.parentElement.parentElement.parentElement, 'completed')){
                        document.getElementById('mark-complete').getElementsByTagName('textarea')[0].value = '';
                        removeClass(document.getElementById('mark-complete'), 'hide');
                        document.getElementById('task-list').style.marginTop = '50px';
                        document.body.scrollTop = 0;
                    } else {
                        var pl = new SOAPClientParameters();
                        pl.add("id", this.parentElement.parentElement.parentElement.parentElement.attributes['id'].value);
                        SOAPClient.invoke('/m/', 'undoComplete', pl, true, function(r){
                            var selected_task = document.getElementsByClassName('mention-head selected')[0].parentElement;
                            removeClass(selected_task, 'completed');
                            selected_task.getElementsByClassName('mark-complete')[0].innerHTML= '<i class="fa fa-check"></i> Mark Complete&nbsp; &nbsp;';
                            removeClass(selected_task.getElementsByClassName('delete')[0], 'hide');
                        });
                    }
                }, false);
                
                //event delete button
                this.parentElement.getElementsByClassName('delete')[0].addEventListener('click', function() {
                    document.getElementById('option').style.marginTop = '0px';
                    document.getElementById('task-list').style.marginTop = '50px';            
                    addClass(document.getElementById('content'), 'hide');
                    removeClass(document.getElementById('loading'), 'hide');
                    //close form
                    var options = document.getElementById('options-button').getElementsByTagName('li');
                    for(var i = 0; i < options.length; i++){
                        if(document.getElementById(options[i].attributes['data'].value) !== null)
                            if(!window.hasClass(document.getElementById(options[i].attributes['data'].value), 'hide')){
                                addClass(document.getElementById(options[i].attributes['data'].value), 'hide');
                                i = options.length;
                            }
                    }
                    //close mark-complete form
                    if(!window.hasClass(document.getElementById('mark-complete'), 'hide')){
                        addClass(document.getElementById('mark-complete'), 'hide');
                    }
                    //request deleting
                    var pl = new SOAPClientParameters();
                    var selected_task = this.parentElement.parentElement.parentElement.parentElement;
                    pl.add("id", selected_task.attributes['id'].value);
                    SOAPClient.invoke("/m/", "deleteTask", pl, true, function(r) {
                        selected_task.parentNode.removeChild(selected_task);
                        //effect load task
                        //show all task
                        var tasks = document.getElementById('task-list').getElementsByClassName('task');
                        for (var i = 0; i < tasks.length; i++) {
                            removeClass(tasks[i], 'hide');
                        }
                        removeClass(document.getElementById('content'), 'hide');
                        addClass(document.getElementById('loading'), 'hide');
                    });
                }, false);
            }
        }, false);
        
        //add event to quote of each task
        if(tasks[i].getElementsByTagName('blockquote')[0] !== undefined){
            tasks[i].getElementsByTagName('blockquote')[0].addEventListener('click', function(e){
                e.stopPropagation();
                var status = this.getElementsByTagName('a')[0].textContent;
                if(status === 'show quote'){
                    this.style.height = '180px';
                    this.getElementsByTagName('a')[0].textContent = 'hide quote';
                } else {
                    this.style.height = '18px';
                    this.getElementsByTagName('a')[0].textContent = 'show quote';
                }
            }, false);
        }
    }
}

function eventTaskOptionBar() {
    //back-button
    document.getElementById('back-button').addEventListener('click', function(){
        document.getElementById('option').style.marginTop = '0px';
        document.getElementById('task-list').style.marginTop = '50px';
        addClass(document.getElementById('social-button').getElementsByTagName('ul')[0], 'hide');
        addClass(document.getElementById('options-button').getElementsByTagName('ul')[0], 'hide');
        addClass(document.getElementById('content'), 'hide');
        removeClass(document.getElementById('loading'), 'hide');

        //close form
        var options = document.getElementById('options-button').getElementsByTagName('li');
        for(var i = 0; i < options.length; i++){
            if(document.getElementById(options[i].attributes['data'].value) !== null)
                if(!window.hasClass(document.getElementById(options[i].attributes['data'].value), 'hide')){
                    addClass(document.getElementById(options[i].attributes['data'].value), 'hide');
                    i = options.length;
                }
        }
        //close mark-complete form
        if(!window.hasClass(document.getElementById('mark-complete'), 'hide')){
            addClass(document.getElementById('mark-complete'), 'hide');
        }
            
        var tasks = document.getElementById('task-list').getElementsByClassName('mention-head');
        for(var i = 0; i < tasks.length; i++){
            removeClass(tasks[i].parentElement, 'hide');
            removeClass(tasks[i], 'selected');
            addClass(tasks[i].parentElement.getElementsByClassName('buzz-task')[0], 'hide');
        }
        //effect load task
        selector = this;
        setTimeout(function(){
            removeClass(document.getElementById('content'), 'hide');
            addClass(document.getElementById('loading'), 'hide');
        }, 200);
    }, false);
    
    //click event on options-button
    document.getElementById('options-button').addEventListener('click', function(){
        if(window.hasClass(this.getElementsByTagName('ul')[0], 'hide')){
            removeClass(this.getElementsByTagName('ul')[0], 'hide');
            addClass(document.getElementById('social-button').getElementsByTagName('ul')[0], 'hide');
            
            //close current form
            var social = document.getElementById('social-button').getElementsByTagName('li');
            for(var i = 0; i < social.length; i++){
                if(document.getElementById(social[i].attributes['data'].value) !== null)
                    if(!window.hasClass(document.getElementById(social[i].attributes['data'].value), 'hide')){
                        addClass(document.getElementById(social[i].attributes['data'].value), 'hide');
                        document.getElementById('task-list').style.marginTop = '90px';
                        return;
                    }
            }
            var options = document.getElementById('options-button').getElementsByTagName('li');
            for(var i = 0; i < options.length; i++){
                if(document.getElementById(options[i].attributes['data'].value) !== null)
                    if(!window.hasClass(document.getElementById(options[i].attributes['data'].value), 'hide')){
                        addClass(document.getElementById(options[i].attributes['data'].value), 'hide');
                        document.getElementById('task-list').style.marginTop = '90px';
                        return;
                    }
            }
        }else{
            addClass(this.getElementsByTagName('ul')[0], 'hide');
        }
    }, false);
    
    //child li of options-button
    var options = document.getElementById('options-button').getElementsByTagName('li');
    for(var i = 0; i < options.length; i++){
        options[i].addEventListener('click', function(e){
            var type = this.attributes['data'].value;
            if(type === 'tags'){
                e.stopPropagation();
            }else {
                for(var j = 0; j < options.length; j++){
                    if(document.getElementById(options[j].attributes['data'].value) !== null)
                        if(!window.hasClass(document.getElementById(options[j].attributes['data'].value), 'hide')){
                            addClass(document.getElementById(options[j].attributes['data'].value), 'hide');
                            j = options.length;
                        }
                }
                var form = document.getElementById(type);
                if(form !== null){
                    document.body.scrollTop = 0;
                    removeClass(form, 'hide');
                    document.getElementById('task-list').style.marginTop = '50px';
                    //reset value
                    var selects = form.getElementsByTagName('select');
                    for (var i = 0; i < selects.length; i++) {
                        selects[i].value = 1;
                    }
                    var inputs = form.getElementsByTagName('input');
                    for (var i = 0; i < inputs.length; i++) {
                        inputs[i].value = '';
                    }
                    var textareas = form.getElementsByTagName('textarea');
                    for (var i = 0; i < textareas.length; i++) {
                        textareas[i].value = '';
                    }
                }
            }
        }, false);
    }
 
    //cancel-button of options
    var cancel_button = document.getElementById('header').getElementsByClassName('cancel');
    for(var i = 0; i < cancel_button.length; i++){
        cancel_button[i].addEventListener('click', function(){
            addClass(this.parentElement.parentElement.parentElement, 'hide');
            document.getElementById('task-list').style.marginTop = '90px';
            
            //reset
            switch(this.attributes['dataType'].value){
                case 'send-sms':
                    var sendSMS_form = document.getElementById('send-sms');
                    sendSMS_form.getElementsByTagName('input')[0].value = '';
                    sendSMS_form.getElementsByTagName('textarea')[0].value = '';
                    break;
                case 'add-task':
                    var addTask_form = document.getElementById('add-task');
                    addTask_form.getElementsByTagName('select')[0].value = 1;
                    addTask_form.getElementsByTagName('select')[1].value = 1;
                    addTask_form.getElementsByTagName('input')[0].value = '';
                    addTask_form.getElementsByTagName('textarea')[0].value = '';
                    break;
                case 'reply':
                    var reply_form = document.getElementById('reply');
                    reply_form.getElementsByTagName('textarea')[0].value = '';
                    break;
                case 'facebook':
                    var shareFacebook_form = document.getElementById('reply');
                    shareFacebook_form.getElementsByTagName('textarea')[0].value = '';
                    break;
                case 'mark-complete':
                    var completeTask_form = document.getElementById('mark-complete');
                    completeTask_form.getElementsByTagName('textarea')[0].value = '';
                    break;
            }
        }, false);
    }
    
    //submit of options
    var submit_button = document.getElementById('header').getElementsByClassName('submit');
    for(var i = 0; i < submit_button.length; i++){
        submit_button[i].addEventListener('click', function(){
            var type = this.attributes['dataType'].value;
            var selected_task = document.getElementsByClassName('mention-head selected')[0].parentElement;
            var pl = new SOAPClientParameters();
            switch(type){
                case 'send-sms':
                    var alert = document.getElementById(type).getElementsByTagName('p')[1];
                    var sendTo = this.parentElement.getElementsByTagName('input')[0].value;
                    var message = this.parentElement.getElementsByTagName('textarea')[0].value;
                    if(sendTo !== '' && message !== ''){
                        pl.add("phoneNumber", sendTo);
                        pl.add("message", message);
                        alert.style.display = 'none';
                        SOAPClient.invoke("/m/", "sendSMS", pl, true, function(r) {
                            var timeout = setTimeout(function() {
                                alert.style.display = '';
                            }, 500);
                        });
                        
                        //reset
                        document.getElementById('task-list').style.marginTop = '90px';
                        addClass(document.getElementById(type), 'hide');
                        this.parentElement.getElementsByTagName('input')[0].value = '';
                        this.parentElement.getElementsByTagName('textarea')[0].value = '';
                    }
                    break;
                case 'add-task':
                    var department = this.parentElement.getElementsByTagName('input')[0].value;
                    var description = this.parentElement.getElementsByTagName('textarea')[0].value;
                    if(department !== ''){
                        var assignedTo = this.parentElement.getElementsByTagName('select')[0].value;
                        var taskType = this.parentElement.getElementsByTagName('select')[1].value;
                        var messageId = selected_task.attributes['messageid'].value;
                        var streamId = selected_task.attributes['streamid'].value;
                        var curLink = document.getElementsByClassName('mention-head selected')[0].getElementsByClassName('title')[0].attributes['href'].value;
                        var currentPost = document.getElementsByClassName('mention-head selected')[0].getElementsByClassName('content')[0].attributes['text'].value;
                        currentPost = currentPost.replace('<span class="readmore-threedot">...</span>', '');
                        pl.add("userId", currentUserId);
                        pl.add("taskType", taskType);
                        pl.add("taskDescription", description);
                        pl.add("assignedTo", assignedTo);
                        pl.add("messageId", messageId);
                        pl.add("streamId", streamId);
                        pl.add("post", '<a href="' + curLink + '" target="_blank">' + currentPost + '</a>');
                        pl.add("department", department);
                        SOAPClient.invoke("/m/", "addTask", pl, true, addTask_callback);
                        
                        //reset
                        document.getElementById('task-list').style.marginTop = '90px';
                        addClass(document.getElementById(type), 'hide');
                        this.parentElement.getElementsByTagName('select')[0].value = 1;
                        this.parentElement.getElementsByTagName('select')[1].value = 1;
                        this.parentElement.getElementsByTagName('input')[0].value = '';
                        this.parentElement.getElementsByTagName('textarea')[0].value = '';
                    }
                    break;
                case 'reply':
                    break;
                case 'facebook':
                    var messageContent = this.parentElement.getElementsByTagName('textarea')[0].value;
                    var shareMessageId = selected_task.attributes['messageid'].value;
                    var shareStreamId = selected_task.attributes['streamid'].value;
                    var messageLink = document.getElementsByClassName('mention-head selected')[0].getElementsByClassName('title')[0].attributes['href'].value;
                    if(messageContent !== ''){
                        pl.add("messageId", shareMessageId);
                        pl.add("streamId", shareStreamId);
                        pl.add("message", messageContent);
                        pl.add("link", messageLink);
                        SOAPClient.invoke("/m/", "postFacebookStatus", pl, true, shareFacebook_callback);
                    }
                    
                    //reset
                    document.getElementById('task-list').style.marginTop = '90px';
                    addClass(document.getElementById(type), 'hide');
                    this.parentElement.getElementsByTagName('textarea')[0].value = '';
                    break;
                case 'mark-complete':
                    var curTaskId = selected_task.attributes['id'].value;
                    var taskAction = document.getElementById('mark-complete').getElementsByTagName('textarea')[0].value;
                    pl = new SOAPClientParameters();
                    pl.add("id", curTaskId);
                    pl.add("action", taskAction);
                    SOAPClient.invoke("/m", "markComplete", pl, true, function(r){
                        var selected_task = document.getElementsByClassName('mention-head selected')[0].parentElement;
                        addClass(selected_task, 'completed');
                        selected_task.getElementsByClassName('mark-complete')[0].innerHTML= '<i class="fa fa-check"></i> Undo Complete&nbsp; &nbsp;';
                        addClass(selected_task.getElementsByClassName('delete')[0], 'hide');
                    });
                    
                    //reset
                    document.getElementById('task-list').style.marginTop = '90px';
                    addClass(document.getElementById(type), 'hide');
                    this.parentElement.getElementsByTagName('textarea')[0].value = '';
                    break;
            }
        }, false);
    }
    
    //social-button
    document.getElementById('social-button').addEventListener('click', function(){
        if(window.hasClass(this.getElementsByTagName('ul')[0], 'hide')){
            removeClass(this.getElementsByTagName('ul')[0], 'hide');
            addClass(document.getElementById('options-button').getElementsByTagName('ul')[0], 'hide');
            
            //close current form
            var social = document.getElementById('social-button').getElementsByTagName('li');
            for(var i = 0; i < social.length; i++){
                if(document.getElementById(social[i].attributes['data'].value) !== null)
                    if(!window.hasClass(document.getElementById(social[i].attributes['data'].value), 'hide')){
                        addClass(document.getElementById(social[i].attributes['data'].value), 'hide');
                        document.getElementById('task-list').style.marginTop = '90px';
                        i = social.length;
                    }
            }
            var options = document.getElementById('options-button').getElementsByTagName('li');
            for(var i = 0; i < options.length; i++){
                if(document.getElementById(options[i].attributes['data'].value) !== null)
                    if(!window.hasClass(document.getElementById(options[i].attributes['data'].value), 'hide')){
                        addClass(document.getElementById(options[i].attributes['data'].value), 'hide');
                        document.getElementById('task-list').style.marginTop = '90px';
                        i = options.length;
                    }
            }
        }else{
            addClass(this.getElementsByTagName('ul')[0], 'hide');
        }
    }, false);
    
    //child li of social-button
    var social = document.getElementById('social-button').getElementsByTagName('li');
    for(var i = 0; i < social.length; i++){
        social[i].addEventListener('click', function(e){
            var type = this.attributes['data'].value;
            for(var j = 0; j < social.length; j++){
                if(document.getElementById(social[j].attributes['data'].value) !== null)
                    if(!window.hasClass(document.getElementById(social[j].attributes['data'].value), 'hide')){
                        addClass(document.getElementById(social[j].attributes['data'].value), 'hide');
                        j = options.length;
                    }
            }
            var form = document.getElementById(type);
            if(form !== null){
                document.body.scrollTop = 0;
                removeClass(form, 'hide');
                document.getElementById('task-list').style.marginTop = '50px';
            }
        }, false);
    }
    
    function shareFacebook_callback(r){

    }
    
    function addTask_callback(r){

    }
    //select of tags
    document.getElementById('tags-option').getElementsByTagName('select')[0].addEventListener('change', function(){
        if(this.value !== 0){
            console.log('ok');
            var tag_bar = document.getElementById('task-list').getElementsByClassName('selected')[0].getElementsByClassName('tag-bar')[0];
            var tag_zone = tag_bar.getElementsByClassName('tag-zone')[0];
            var tags = tag_bar.getElementsByClassName('tag');
            var tagId = this.value;
            var streamId = tag_bar.parentElement.parentElement.attributes['streamid'].value;
            var messageId = tag_bar.parentElement.parentElement.attributes['messageid'].value;

            //create tagNode
            var tag = document.createElement('div');
            tag.setAttribute('class', 'tag new');
            var namediv = document.createElement('div');
            namediv.setAttribute('class', 'name');
            namediv.textContent = '#' + this.options[this.selectedIndex].text;
            tag.appendChild(namediv);
            var del = document.createElement('div');
            del.setAttribute('class', 'del');
            del.textContent = 'x';
            tag.appendChild(del);

            //delete event of Tag
            tag.getElementsByTagName('div')[1].addEventListener('click', function(){
                var pl = new SOAPClientParameters();
                pl.add('tagId', tagId);
                pl.add('streamId', streamId);
                pl.add('messageId', messageId);
                SOAPClient.invoke('/m/', 'removeTag', pl, true, function() {
                    tag.parentNode.removeChild(tag);
                    tags = tag_bar.getElementsByClassName('tag');
                    var tags_width = 0;
                    for(var i = 0; i < tags.length; i++){
                        tags_width += tags[i].clientWidth + 5;
                    }
                    if(tags_width + 32 <= tag_zone.clientWidth) {
                        addClass(tag_zone.getElementsByClassName('threedot')[0], 'hide');
                        removeClass(tag_zone, 'expanded');
                    }
                    if(tags.length < 2){
                        addClass(tag_bar, 'hide');
                    }
                });
            }, false);

            //show tag-bar
            if(window.hasClass(tag_bar, 'hide')){
                removeClass(tag_bar, 'hide');
            }

            //add Tag
            tag_zone.appendChild(tag);
            var pl = new SOAPClientParameters();
            pl.add("messageId", messageId);
            pl.add("tagId", tagId);
            pl.add("streamId", streamId);
            SOAPClient.invoke("/m/", "addTag", pl, true, null);

            //show expanded
            var tags_width = 0;
            for(var i = 0; i < tags.length; i++){
                tags_width += tags[i].clientWidth + 5;
            }
            if(tags_width + 32 > tag_zone.clientWidth){
                removeClass(tag_zone.getElementsByClassName('threedot')[0], 'hide');
            }
            removeClass(tag_zone.getElementsByClassName('new')[0], 'new');

            //effect fix error with Safari browser
            temp = this.options[this.selectedIndex].text;
            this.options[this.selectedIndex].text = 'Tags';
            selector = this;
            setTimeout(function(){
                selector.options[selector.selectedIndex].text = temp;
                selector.value = '0';
                selector.selectedIndex = 0;
            }, 100);
        }
    },false);
}

var engagement_viewport = function(data){
    viewport.innerHTML = data;
    dateFrom = document.getElementById('datefrom-filter').attributes['value'].value;
    dateTo = document.getElementById('dateto-filter').attributes['value'].value;
    
    //edit link in main-section of viewport
    var main_section = document.getElementById('main-section');
    var engagement_section = main_section.getElementsByClassName('fa-engagement')[0].parentElement;
    var compare_section = main_section.getElementsByClassName('fa-comparison')[0].parentElement;
    var mention_section = main_section.getElementsByClassName('ub-mention')[0].parentElement;
    var metrics_section = main_section.getElementsByClassName('ub-metrics')[0].parentElement;
    engagement_section.attributes['href'].value += streamId;
    compare_section.attributes['href'].value += streamId;
    mention_section.attributes['href'].value += streamId;
    metrics_section.attributes['href'].value += streamId;
    
    addEventMainSection();
    
    //load engagement_mainview
    sendRequest("engagement/" + params[1] + "/mainview", engagement_mainview, process);
};
var engagement_mainview = function(data) {
    controller.innerHTML = data;
    exec_body_scripts(controller);
    document.getElementById('option').style.marginTop = '50px';
    document.getElementById('content').style.marginTop = '90px';
    //set button of option
    var buttons = document.getElementById('option').getElementsByTagName('a');
    buttons[0].attributes['href'].value += streamId;
    buttons[1].attributes['href'].value += streamId;
    addEventTopBanner();
};

var compare_viewport = function(data){
    viewport.innerHTML = data;
    dateFrom = document.getElementById('datefrom-filter').attributes['value'].value;
    dateTo = document.getElementById('dateto-filter').attributes['value'].value;
    if(firstViewport){
        firstViewport = false;
        sendRequest("compare/" + params[1] + "/mainview", compare_mainview, process);
    }
    
    //edit link in main-section of viewport
    var main_section = document.getElementById('main-section');
    var engagement_section = main_section.getElementsByClassName('fa-engagement')[0].parentElement;
    var compare_section = main_section.getElementsByClassName('fa-comparison')[0].parentElement;
    var mention_section = main_section.getElementsByClassName('ub-mention')[0].parentElement;
    var metrics_section = main_section.getElementsByClassName('ub-metrics')[0].parentElement;
    engagement_section.attributes['href'].value += streamId;
    compare_section.attributes['href'].value += streamId;
    mention_section.attributes['href'].value += streamId;
    metrics_section.attributes['href'].value += streamId;
    
    addEventMainSection();
};

var compare_mainview = function(data) {
    controller.innerHTML = data;
    exec_body_scripts(controller);
    document.getElementById('option').style.marginTop = '50px';
    
    //set button of option
    var buttons = document.getElementById('option').getElementsByTagName('a');
    buttons[0].attributes['href'].value += streamId;
    buttons[1].attributes['href'].value += streamId;
    
    addEventTopBanner();
};

var metrics_viewport = function(data){
    viewport.innerHTML = data;
    dateFrom = document.getElementById('datefrom-filter').attributes['value'].value;
    dateTo = document.getElementById('dateto-filter').attributes['value'].value;
    
    //edit link in main-section of viewport
    var main_section = document.getElementById('main-section');
    var engagement_section = main_section.getElementsByClassName('fa-engagement')[0].parentElement;
    var compare_section = main_section.getElementsByClassName('fa-comparison')[0].parentElement;
    var mention_section = main_section.getElementsByClassName('ub-mention')[0].parentElement;
    var metrics_section = main_section.getElementsByClassName('ub-metrics')[0].parentElement;
    engagement_section.attributes['href'].value += streamId;
    compare_section.attributes['href'].value += streamId;
    mention_section.attributes['href'].value += streamId;
    metrics_section.attributes['href'].value += streamId;
    
    addEventMainSection();
};

var metrics_mainview = function(data){
    controller.innerHTML = data;
    loadScript(["/JS/Mobile/raphael-min.js"], function(d){
        loadScript(["/JS/Mobile/graphSupporter.js"], function(d) {
            document.getElementById('option').style.marginTop = '50px';
            document.getElementById('content').style.marginTop = '90px';
            //set button of option
            var buttons = document.getElementById('option').getElementsByTagName('a');
            buttons[0].attributes['href'].value += streamId;
            buttons[1].attributes['href'].value += streamId;

            addEventTopBanner();
            loadMetrics();
        });
    });
};

var settings_mainview = function(data){
    controller.innerHTML = data;
    document.body.scrollTop = 0;
    addEventTopBanner();
    switch(params[1]){
        case "account":
            if(document.getElementById('current-password') === null){
                addClass(document.getElementById('loading'), 'hide');
            }
            loadScript(["JS/Mobile/md5.js"], function(){
                addEventAccount();});
            break;
        case "folders":
            currentFolderId = '0';
            document.getElementById('option').style.marginTop = '50px';
            document.getElementById('content').style.marginTop = '90px';
            var pl = new SOAPClientParameters();
            SOAPClient.invoke("/m/", "getFolder", pl, true, getfolder_callback);
            break;
        case "tags":
            currentTagGroupId = '0';
            document.getElementById('option').style.marginTop = '50px';
            document.getElementById('content').style.marginTop = '90px';
            var pl = new SOAPClientParameters();
            SOAPClient.invoke("/m/", "getGroups", pl, true, getGroups_callback);
            break;
        case "connected-accounts":
            document.getElementById('option').style.marginTop = '50px';
            document.getElementById('content').style.marginTop = '90px';
            addEventOptionConnectedAccount();
            var pl = new SOAPClientParameters();
            SOAPClient.invoke("/m/", "getAccounts", pl, true, getaccounts_callback);
            break;
        case "groups":
            document.getElementById('option').style.marginTop = '50px';
            document.getElementById('content').style.marginTop = '90px';
            var pl = new SOAPClientParameters();
            SOAPClient.invoke("/m/", "getUser", pl, true, getuser_callback);
            break;
    }
};

function getuser_callback(r) {
    addClass(document.getElementById('loading'), 'hide');
    document.getElementById('user-list').innerHTML = '';
    if (r["userid"] !== undefined) {
        var userid = r["userid"].split(';');
        var username = r["username"].split(';');
        var usermail = r["usermail"].split(';');
        var lastlogin = r["lastlogin"].split(';');
        var avatar = r['avatar'].split(';');
        var li = '';
        for(var i = 0; i < userid.length; i++){
            li += '<li class="folder hide" data-id="' + userid[i] + '" data-email="' + usermail[i] + '" last-login="' + lastlogin[i] + '">' +
                    '<div class="ico" avatar="' + avatar[i] + '">' +
                        '<i class="fa fa-folder fa-2x t-yellow"></i>' +
                    '</div>' +
                    '<div class="name">' + username[i] + '</div>' +
                    '<div class="action">' +
                        '<i class="fa fa-edit fa-1x5 t-grey"></i>' +
                        '&nbsp; &nbsp; &nbsp;' +
                        '<i class="fa fa-trash-o fa-1x5 t-grey delete"></i> &nbsp; &nbsp;' +
                    '</div>' +
                '</li>';
        }
        document.getElementById('user-list').innerHTML += li;
    }
}

function getGroups_callback(r){
    var groups = JSON.parse(r);
    addClass(document.getElementById('loading'), 'hide');
    document.getElementById('tag-list').innerHTML = '';
    var li = '<li class="back hide">' +
                '<div class="ico">' +
                    '<i class="fa fa-folder fa-2x t-yellow"></i>' +
                '</div>' +
                '<div class="name">...</div>' +
            '</li>';
    for(var i = 0; i < groups.length; i++){
        li += '<li class="tag-group" data-id="' + groups[i].groupid + '">' +
                '<div class="ico">' +
                    '<i class="fa fa-folder fa-2x t-yellow"></i>' +
                '</div>' +
                '<div class="name">' + groups[i].groupname + '</div>' +
            '</li>';
    }
    document.getElementById('tag-list').innerHTML += li;
    //load tag in each groups
    var pl = new SOAPClientParameters();
    pl.add('groupId', 0);
    SOAPClient.invoke("/m/", "listTag", pl, true, listtag_callback);
}

function listtag_callback(r){
    if(r !== 'null'){
        var tags = JSON.parse(r);
        var li = '';
        for(var i = 0; i < tags.length; i++){
            li += '<li class="tag hide" group-id="' + tags[i].groupId + '">' +
                    '<div class="ico">' +
                        '<i class="ub ub-streams ub-2x t-green"></i>' +
                    '</div>' +
                    '<div class="name">' + tags[i].tagName + '</div>' +
                '</li>';
        }
        document.getElementById('tag-list').innerHTML += li;
    }
    addEventTagView();
}

function getaccounts_callback(r) {
    if (r["screenname"] !== 'undefined' && r["accountid"] !== 'undefined') {
        var li = '';
        var screenname_twitter = r["screenname"].split('twitter')[0];
        var id_twitter = r["accountid"].split('twitter')[0];
        var screenname_facebook = r["screenname"].split('twitter')[1].split('facebook')[0];
        var id_facebook = r["accountid"].split('twitter')[1].split('facebook')[0];
        var screenname_google = r["screenname"].split('facebook')[1].split('google')[0];
        var id_google = r["accountid"].split('facebook')[1].split('google')[0];
        var screenname_linkedin = r["screenname"].split('google')[1].split('linkedin')[0];
        var id_linkedin = r["accountid"].split('google')[1].split('linkedin')[0];
        var twitterscreenname = screenname_twitter.split(';');
        var twitterid = id_twitter.split(';');
        for (var i = 0; i < twitterscreenname.length - 1; i++) {
            li += '<li class="twitter">' +
                        '<div class="ico">' +
                            '<img src="Images/social-twitter.png" alt="">' +
                        '</div>' +
                        '<div class="name"><p>' + twitterscreenname[i] + '</p><span>' + twitterid[i] + '</span></div>' +
                        '<div class="action">' +
                            '<i class="fa fa-edit fa-1x5 t-grey"></i> &nbsp; &nbsp; &nbsp; &nbsp;' +
                            '<i class="fa fa-trash-o fa-1x5 t-grey delete"></i>' +
                        '</div>' +
                   ' </li>';
        }
        var facebookscreenname = screenname_facebook.split(';');
        var facebookid = id_facebook.split(';');
        for (i = 0; i < facebookscreenname.length - 1; i++) {
            li += '<li class="facebook">' +
                        '<div class="ico">' +
                            '<img src="Images/social-facebook.png" alt="">' +
                        '</div>' +
                        '<div class="name"><p>' + facebookscreenname[i] + '</p><span>' + facebookid[i] + '</span></div>' +
                        '<div class="action">' +
                            '<i class="fa fa-edit fa-1x5 t-grey"></i> &nbsp; &nbsp; &nbsp; &nbsp;' +
                            '<i class="fa fa-trash-o fa-1x5 t-grey delete"></i>' +
                        '</div>' +
                   ' </li>';
       }
        var googlescreenname = screenname_google.split(';');
        var googleid = id_google.split(';');
        for (i = 0; i < googlescreenname.length - 1; i++) {
            li += '<li class="googleplus">' +
                        '<div class="ico">' +
                            '<img src="Images/social-gplus.png" alt="">' +
                        '</div>' +
                        '<div class="name"><p>' + googlescreenname[i] + '</p><span>' + googleid[i] + '</span></div>' +
                        '<div class="action">' +
                            '<i class="fa fa-edit fa-1x5 t-grey"></i> &nbsp; &nbsp; &nbsp; &nbsp;' +
                            '<i class="fa fa-trash-o fa-1x5 t-grey delete"></i>' +
                        '</div>' +
                   ' </li>';
        }
        var linkedinscreenname = screenname_linkedin.split(';');
        var linkedinid = id_linkedin.split(';');
        for (i = 0; i < linkedinscreenname.length - 1; i++) {
            li += '<li class="linkedin">' +
                        '<div class="ico">' +
                            '<img src="Images/social-linkedin.png" alt="">' +
                        '</div>' +
                        '<div class="name"><p>' + linkedinscreenname[i] + '</p><span>' + linkedinid[i] + '</span></div>' +
                        '<div class="action">' +
                            '<i class="fa fa-edit fa-1x5 t-grey"></i> &nbsp; &nbsp; &nbsp; &nbsp;' +
                            '<i class="fa fa-trash-o fa-1x5 t-grey delete"></i>' +
                        '</div>' +
                   ' </li>';
        }
        document.getElementById('account-list').innerHTML = li;
    } else {
        document.getElementById('account-list').innerHTML = '';
    }
    addClass(document.getElementById('loading'), 'hide');
    addEventConnectedAccount();
}

function addEventOptionConnectedAccount(){
    //add event change value of social-account
    document.getElementById('social-account').addEventListener('change', function(){
        var li = document.getElementById('account-list').getElementsByTagName('li');
        for(var i = 0; i < li.length; i++){
            if(this.value === "all_account"){
                removeClass(li[i], 'hide');
            } else {
                if(window.hasClass(li[i], this.value)){
                    removeClass(li[i], 'hide');
                } else {
                    addClass(li[i], 'hide');
                }
            }
        }
    }, false);
    //add event add social_account button
    document.getElementById('add-social').addEventListener('click', function(){
        if(window.hasClass(document.getElementById('menu-social'), 'hide')){
            removeClass(document.getElementById('menu-social'), 'hide');
        } else {
            addClass(document.getElementById('menu-social'), 'hide');
        }
    }, false);
    //add event add social_account
    var add_account = document.getElementById('menu-social').getElementsByTagName('li');
    for(var i = 0; i < add_account.length; i++){
        add_account[i].addEventListener('click', function(){
            addClass(document.getElementById('menu-social'), 'hide');
            var type = this.textContent.trim();
            var pl = new SOAPClientParameters();
            switch(type){
                case 'Twitter':
                    SOAPClient.invoke("/m/", "getTwitters", pl, true, hastwitter_callback);
                    break;
                case 'Facebook':
                    SOAPClient.invoke("/m/", "getFacebooks", pl, true, hasfacebook_callback);
                    break;
                case 'Google+':
                    SOAPClient.invoke("/m/", "getGoogles", pl, true, hasgoogle_callback);
                    break;
                case 'Linkedin':
                    SOAPClient.invoke("/m/", "getLinkedIns", pl, true, haslinkedin_callback);
                    break;
            }
        }, false);
    }
}

function addEventConnectedAccount(){
    //add event delete social_account
    var delete_account = document.getElementById('account-list').getElementsByClassName('delete');
    for(var i = 0; i < delete_account.length; i++){
        delete_account[i].addEventListener('click', function(){
            var pl = new SOAPClientParameters();
            var id = this.parentElement.parentElement.getElementsByClassName('name')[0].getElementsByTagName('span')[0].textContent;
            var type = this.parentElement.parentElement.attributes['class'].value;
            switch (type) {
                case 'twitter':
                    pl.add("twitterid", id);
                    SOAPClient.invoke("/m/", "deleteTwitter", pl, true, deletetSocialComplete);
                    break;
                case 'facebook':
                    pl.add("facebookid", id);
                    SOAPClient.invoke("/m/", "deleteFacebook", pl, true, deletetSocialComplete);
                    break;
                case 'googleplus':
                    pl.add("googleid", id);
                    SOAPClient.invoke("/m/", "deleteGoogle", pl, true, deletetSocialComplete);
                    break;
                case 'linkedin':
                    pl.add("linkedinid", id);
                    SOAPClient.invoke("/m/", "deleteLinkedIn", pl, true, deletetSocialComplete);
                    break;

            }
        }, false);
    }
}

function hastwitter_callback(r){
    if (r["screenname"] === 'undefined') {
        var win = window.open('authorizeTwitter');
        var ttimer = setInterval(function() {
            if (win.closed) {
                clearInterval(ttimer);
                var pl = new SOAPClientParameters();
                SOAPClient.invoke("/m/", "getAccounts", pl, true, getaccounts_callback);
            }
        }, 1000);
    }
}
function hasfacebook_callback(r) {
    if (r["screenname"] === 'undefined') {
        var win = window.open('authorizeFacebook');
        var ttimer = setInterval(function() {
            if (win.closed) {
                clearInterval(ttimer);
                var pl = new SOAPClientParameters();
                SOAPClient.invoke("/m/", "getAccounts", pl, true, getaccounts_callback);
            }
        }, 1000);
    }
}

function hasgoogle_callback(r) {
    if (r["screenname"] === 'undefined') {
        var win = window.open('authorizeGoogle');
        var ttimer = setInterval(function() {
            if (win.closed) {
                clearInterval(ttimer);
                var pl = new SOAPClientParameters();
                SOAPClient.invoke("/m/", "getAccounts", pl, true, getaccounts_callback);
            }
        }, 1000);
    }
}

function haslinkedin_callback(r) {
    if (r["screenname"] === 'undefined') {
        var win = window.open('authorizeLinkedIn');
        var ttimer = setInterval(function() {
            if (win.closed) {
                clearInterval(ttimer);
                var pl = new SOAPClientParameters();
                SOAPClient.invoke("/m/", "getAccounts", pl, true, getaccounts_callback);
            }
        }, 1000);
    }
}
    
function deletetSocialComplete(r) {
    if (r === "true") {
        var pl = new SOAPClientParameters();
        SOAPClient.invoke("/m/", "getAccounts", pl, true, getaccounts_callback);
    }
}

function getfolder_callback(r){
    addClass(document.getElementById('loading'), 'hide');
    document.getElementById('folder-list').innerHTML = '';
    var li = '<li class="back hide">' +
                '<div class="ico">' +
                    '<i class="fa fa-folder fa-2x t-yellow"></i>' +
                '</div>' +
                '<div class="name">...</div>' +
            '</li>';
    if(r["folderid"] !== undefined){
        //add folder to folder-list
        var folderid = r["folderid"].split(';');
        var foldername = r["foldername"].split(';');
        var parentid = r["parentid"].split(';');
        for(var i = 0; i < folderid.length; i++){
            if(parentid[i] === '0'){
                li += '<li class="folder" data-id="' + folderid[i] + '" parent-id="' + parentid[i] + '">' +
                        '<div class="ico">' +
                            '<i class="fa fa-folder fa-2x t-yellow"></i>' +
                        '</div>' +
                        '<div class="name">' + foldername[i] + '</div>' +
                        '<div class="action">' +
                            '<i class="fa fa-edit fa-1x5 t-grey"></i>' +
                            '&nbsp; &nbsp; &nbsp;' +
                            '<i class="fa fa-trash-o fa-1x5 t-grey delete"></i> &nbsp; &nbsp;' +
                        '</div>' +
                    '</li>';
            } else {
                li += '<li class="folder hide" data-id="' + folderid[i] + '" parent-id="' + parentid[i] + '">' +
                        '<div class="ico">' +
                            '<i class="fa fa-folder fa-2x t-yellow"></i>' +
                        '</div>' +
                        '<div class="name">' + foldername[i] + '</div>' +
                        '<div class="action">' +
                            '<i class="fa fa-edit fa-1x5 t-grey"></i>' +
                            '&nbsp; &nbsp; &nbsp;' +
                            '<i class="fa fa-trash-o fa-1x5 t-grey delete"></i> &nbsp; &nbsp;' +
                        '</div>' +
                    '</li>';
            }
        }
        document.getElementById('folder-list').innerHTML += li;
        //load stream in each folder
        var pl = new SOAPClientParameters();
        pl.add('folderid', 0);
        SOAPClient.invoke("/m/", "listStream", pl, true, liststream_callback);
    }
}

function liststream_callback(r){
    if (r["streamid"] !== "undefined") {
        var streamid = r["streamid"].split(';');
        var streamname = r["streamname"].split(';');
        var folderid = r["folderid"].split(';');
        var li = '';
        for(var i = 0; i < streamid.length; i++){
            li += '<li class="stream hide" data-id="' + Base64.encode(streamid[i]) + '" folder-id="' + folderid[i] + '">' +
                        '<div class="ico">' +
                            '<i class="ub ub-streams ub-2x t-green"></i>' +
                        '</div>' +
                        '<div class="name"><a href="/#stream/' + Base64.encode(streamid[i]) + '">' + streamname[i] + '</a></div>' +
                    '</li>';
        }
        document.getElementById('folder-list').innerHTML += li;
    }
    addEventFolderView();
}

function addEventTagView(){
    //add event to each folder
    var groups = document.getElementById('tag-list').getElementsByClassName('tag-group');
    for(var i = 0; i < groups.length; i++){
        groups[i].addEventListener('click', function(){
            currentTagGroupId = this.attributes['data-id'].value;
            //change group name on option title
            //check curGroupName to back group
            for(var j = 0; j < groups.length; j++){
                if(groups[j].attributes['data-id'].value === currentTagGroupId){
                    curGroupName = groups[j].getElementsByClassName('name')[0].textContent.toUpperCase();
                }
            }
            document.getElementById('tag-name').innerHTML = '<i style="float:left; margin-left:10px;width:30px;">&nbsp; &nbsp;</i>' +		
                                                                this.getElementsByClassName('name')[0].textContent.toUpperCase() +
                                                                '<i class="ub ub-plus ub-lg add" style="float: right;width:30px; margin-top:8px; margin-right:10px;"></i>';
            eventShowAddTagForm();
            //show back group
            removeClass(document.getElementById('tag-list').getElementsByClassName('back')[0], 'hide');
            //hide all groups and...
            for(var j = 0; j < groups.length; j++){
                addClass(groups[j], 'hide');
            }
            //show tag
            var tags = document.getElementById('tag-list').getElementsByClassName('tag');
            for(var j = 0; j < tags.length; j++){
                if(tags[j].attributes['group-id'].value === currentTagGroupId){
                    removeClass(tags[j], 'hide');
                }
            }
            //close add-tag-group form
            document.getElementById('add-tag-group').getElementsByClassName('name')[0].value = '';
            addClass(document.getElementById('add-tag-group'), 'hide');
            document.getElementById('content').style.marginTop = '90px';
        }, false);
    }
    
    //add event to back folder
    document.getElementById('tag-list').getElementsByClassName('back')[0].addEventListener('click', function(){
        //check curGroupName to back group
        document.getElementById('tag-name').innerHTML = '<i style="float:left; margin-left:10px;width:30px;">&nbsp; &nbsp;</i>' +		
                                                        'TAGS<i class="ub ub-plus ub-lg add" style="float: right;width:30px; margin-top:8px; margin-right:10px;"></i>';
        eventShowAddTagForm();
        //hide back group
        addClass(this, 'hide');
        //hide all stream and...
        var tags = document.getElementById('tag-list').getElementsByClassName('tag');
        for(var i = 0; i < tags.length; i++){
            addClass(tags[i], 'hide');
        }
        //show all groups
        var groups = document.getElementById('tag-list').getElementsByClassName('tag-group');
        for(var i = 0; i < groups.length; i++){
            removeClass(groups[i], 'hide');
        }
        currentTagGroupId = '0';
        //close add-tag-group form
        document.getElementById('add-tag-group').getElementsByClassName('name')[0].value = '';
        addClass(document.getElementById('add-tag-group'), 'hide');
        document.getElementById('content').style.marginTop = '90px';
    }, false);
    
    //add event show ADD TAG GROUP form
    eventShowAddTagForm();
    //add event add button in ADD TAG GROUP form
    document.getElementById('add-tag-group').getElementsByClassName('submit')[0].addEventListener('click', function(){
        if(currentTagGroupId === '0'){
            var group_name = document.getElementById('add-tag-group').getElementsByClassName('name')[0].value;
            if(group_name !== ''){
                var pl = new SOAPClientParameters();
                pl.add('groupName', group_name);
                SOAPClient.invoke("/m/", "addTagGroup", pl, true, addtaggroup_callback);
                document.getElementById('add-tag-group').getElementsByClassName('name')[0].value = '';
            }
        } else {
            var tag_name = document.getElementById('add-tag-group').getElementsByClassName('name')[0].value;
            if(tag_name !== ''){
                var pl = new SOAPClientParameters();
                pl.add("tagName", tag_name);
                pl.add("tagKeywords", tagKeywords.join(','));
                pl.add("groupId", currentTagGroupId);
                SOAPClient.invoke("/m/", "createTag", pl, true, createTag_complete);
                document.getElementById('add-tag-group').getElementsByClassName('name')[0].value = '';
            }
        }
    }, false);
    
    //add event cancel button in TAG GROUP form
    document.getElementById('add-tag-group').getElementsByClassName('cancel')[0].addEventListener('click', function(){
        document.getElementById('add-tag-group').getElementsByClassName('name')[0].value = '';
        addClass(document.getElementById('add-tag-group'), 'hide');
        document.getElementById('content').style.marginTop = '90px';
    }, false);
    
    //add event change text of input Keywords
    width = 10;
    document.getElementById('keywords_input').addEventListener('input', function(){
        width += 10;
        this.style.width = width + 'px';
        var last_char = this.value.substring(this.value.length - 1, this.value.length);
        if(last_char === ','){
            var data_presenting = document.getElementById('add-tag-group').getElementsByClassName('data-presenting')[0];
            //create node keyword
            var span = document.createElement('span');
            span.setAttribute('class', 'email');
            span.setAttribute('email', this.value.substring(0, this.value.length - 1));
            span.textContent = this.value.substring(0, this.value.length - 1);
            var i = document.createElement('i');
            i.setAttribute('class', 'fa fa-clear');
            span.appendChild(i);
            //add icon to node and add tagKeywords array
            tagKeywords.push(this.value.substring(0, this.value.length - 1));
            
            //add event delete to node
            i.addEventListener('click', function(){
                var position = tagKeywords.indexOf(i.parentNode.textContent);
                data_presenting.removeChild(i.parentElement);
                tagKeywords = tagKeywords.slice(0, position).concat(tagKeywords.slice(position + 1, tagKeywords.length));
            }, false);
            
            //reset
            this.value = '';
            this.style.width = '7.3px';
            width = 10;
            //add node to data-presenting
            data_presenting.insertBefore(span, this.parentNode);
        }
    }, false);
    
    //add event lost focus of input Keywords
    document.getElementById('keywords_input').addEventListener('blur', function(){
        if(this.value !== ''){
            var data_presenting = document.getElementById('add-tag-group').getElementsByClassName('data-presenting')[0];
            //create node keyword
            var span = document.createElement('span');
            span.setAttribute('class', 'email');
            span.setAttribute('email', this.value.substring(0, this.value.length - 1));
            span.textContent = this.value.substring(0, this.value.length - 1);
            var i = document.createElement('i');
            i.setAttribute('class', 'fa fa-clear');
            span.appendChild(i);
            tagKeywords.push(this.value.substring(0, this.value.length - 1));
            
            //add event delete to node
            i.addEventListener('click', function(){
                var position = tagKeywords.indexOf(i.parentNode.textContent);
                data_presenting.removeChild(i.parentElement);
                tagKeywords = tagKeywords.slice(0, position).concat(tagKeywords.slice(position + 1, tagKeywords.length));
            }, false);
            
            //reset
            this.value = '';
            this.style.width = '7.3px';
            width = 10;
            //add node to data-presenting
            data_presenting.insertBefore(span, this.parentNode);
        }
    }, false);
    
    //change focus from div to input keyword
    document.getElementById('add-tag-group').getElementsByClassName('data-presenting')[0].addEventListener('click', function(){
        document.getElementById('keywords_input').focus();
        addClass(this, 'focus');
    }, false);
    
    //add event all tags
    document.getElementById('all-tags').addEventListener('click', function(){
        //change GroupName on option title
        document.getElementById('tag-name').innerHTML = '<i style="float:left; margin-left:10px;width:30px;">&nbsp; &nbsp;</i>' +		
                                                        'TAGS<i class="ub ub-plus ub-lg add" style="float: right;width:30px; margin-top:8px; margin-right:10px;"></i>';
        eventShowAddTagForm();
        //show back group
        removeClass(document.getElementById('tag-list').getElementsByClassName('back')[0], 'hide');
        //hide all groups and...
        var groups = document.getElementById('tag-list').getElementsByClassName('tag-group');
        for(var j = 0; j < groups.length; j++){
            addClass(groups[j], 'hide');
        }
        //show all tags
        var tags = document.getElementById('tag-list').getElementsByClassName('tag');
        for(var j = 0; j < tags.length; j++){
            removeClass(tags[j], 'hide');
        }
        //close add-tag-group form
        document.getElementById('add-tag-group').getElementsByClassName('name')[0].value = '';
        addClass(document.getElementById('add-tag-group'), 'hide');
        document.getElementById('content').style.marginTop = '90px';
    }, false);
}

function eventShowAddTagForm() {
    document.getElementById('option').getElementsByClassName('add')[0].addEventListener('click', function(){
        if(currentTagGroupId === '0'){
            document.getElementById('add-tag-group').getElementsByClassName('title')[0].getElementsByTagName('p')[0].textContent = 'CREATE GROUP';
            document.getElementById('add-tag-group').getElementsByClassName('name')[0].placeholder = 'Group Name';
            addClass(document.getElementById('add-tag-group').getElementsByClassName('keywords')[0], 'hide');
        } else {
            //remove span Node in data-presenting
            var data_presenting = document.getElementById('add-tag-group').getElementsByClassName('data-presenting')[0];
            removeClass(data_presenting, 'focus');
            var span = data_presenting.getElementsByClassName('email');
            for(var i = 0; i < span.length;){
                data_presenting.removeChild(span[i]);
            }
            tagKeywords = [];
            document.getElementById('add-tag-group').getElementsByClassName('title')[0].getElementsByTagName('p')[0].textContent = 'CREATE TAG';
            document.getElementById('add-tag-group').getElementsByClassName('name')[0].placeholder = 'Tag Name';
            removeClass(document.getElementById('add-tag-group').getElementsByClassName('keywords')[0], 'hide');
        }
        document.getElementById('add-tag-group').getElementsByClassName('name')[0].value = '';
        removeClass(document.getElementById('add-tag-group'), 'hide');
        document.getElementById('content').style.marginTop = '50px';
    }, false);
}

function addEventFolderView(){
    //add event to each folder
    var folders = document.getElementById('folder-list').getElementsByClassName('folder');
    for(var i = 0; i < folders.length; i++){
        folders[i].addEventListener('click', function(){
            currentFolderId = this.attributes['data-id'].value;
            curParentId = this.attributes['parent-id'].value;
            //change folder name on option title
            //check curFolderName to back folder
            for(var j = 0; j < folders.length; j++){
                if(folders[j].attributes['data-id'].value === curParentId){
                    curFolderName = folders[j].getElementsByClassName('name')[0].textContent.toUpperCase();
                }
            }
            document.getElementById('folder-name').innerHTML = '<i style="float:left; margin-left:10px;width:30px;">&nbsp; &nbsp;</i>' +		
                                                                this.getElementsByClassName('name')[0].textContent.toUpperCase() +
                                                                '<i class="ub ub-plus ub-lg add" style="float: right;width:30px; margin-top:8px; margin-right:10px;"></i>';
            eventShowAddFolderForm();
            //show back folder
            removeClass(document.getElementById('folder-list').getElementsByClassName('back')[0], 'hide');
            if(curParentId === '0'){
                //hide all folders and show all folder which have parentid == parentId
                for(var j = 0; j < folders.length; j++){
                    if(folders[j].attributes['parent-id'].value === currentFolderId){
                        removeClass(folders[j], 'hide');
                    } else {
                        addClass(folders[j], 'hide');
                    }
                }
            } else {
                //hide all folders and...
                for(var j = 0; j < folders.length; j++){
                    addClass(folders[j], 'hide');
                }
                //show stream
                var streams = document.getElementById('folder-list').getElementsByClassName('stream');
                for(var j = 0; j < streams.length; j++){
                    if(streams[j].attributes['folder-id'].value === currentFolderId){
                        removeClass(streams[j], 'hide');
                    }
                }
                //hide add folder button when in streams
                addClass(document.getElementById('option').getElementsByTagName('i')[0], 'hide');
                addClass(document.getElementById('option').getElementsByTagName('i')[1], 'hide');
            }
            //close add-folder form
            document.getElementById('add-folder').getElementsByClassName('name')[0].value = '';
            addClass(document.getElementById('add-folder'), 'hide');
            document.getElementById('content').style.marginTop = '90px';
        }, false);
    }
    
    //add event add button in ADD FOLDER form
    document.getElementById('add-folder').getElementsByClassName('submit')[0].addEventListener('click', function(){
        if(cur)
        var folder_name = document.getElementById('add-folder').getElementsByClassName('name')[0].value;
        if(folder_name !== ''){
            var pl = new SOAPClientParameters();
            pl.add('folderName', folder_name);
            pl.add('parentId', currentFolderId);;
            SOAPClient.invoke("/m/", "addFolder", pl, true, addfolder_callback);
            document.getElementById('add-folder').getElementsByClassName('name')[0].value = '';
        }
    }, false);
    
    //add event cancel button in ADD FOLDER form
    document.getElementById('add-folder').getElementsByClassName('cancel')[0].addEventListener('click', function(){
        document.getElementById('add-folder').getElementsByClassName('name')[0].value = '';
        addClass(document.getElementById('add-folder'), 'hide');
        document.getElementById('content').style.marginTop = '90px';
    }, false);
    
    //add event to back folder
    document.getElementById('folder-list').getElementsByClassName('back')[0].addEventListener('click', function(){
        //show add folder button when back folder
        if(window.hasClass(document.getElementById('option').getElementsByClassName('add')[0], 'hide')){
            removeClass(document.getElementById('option').getElementsByTagName('i')[0], 'hide');
            removeClass(document.getElementById('option').getElementsByTagName('i')[1], 'hide');
        }
        //hide back folder when stay in root
        if(curParentId === '0'){
            addClass(this, 'hide');
            //change folder name on option title
            document.getElementById('folder-name').innerHTML = '<i style="float:left; margin-left:10px;width:30px;">&nbsp; &nbsp;</i>' +
                    'FOLDERS<i class="ub ub-plus ub-lg add" style="float: right;width:30px; margin-top:8px; margin-right:10px;"></i>';
            eventShowAddFolderForm();
        } else {
            //change folder name on option title
            document.getElementById('folder-name').innerHTML = '<i style="float:left; margin-left:10px;width:30px;">&nbsp; &nbsp;</i>' +		
                                                                curFolderName +
                                                                '<i class="ub ub-plus ub-lg add" style="float: right;width:30px; margin-top:8px; margin-right:10px;"></i>';
            eventShowAddFolderForm();
        }
        //hide all stream and folders
        //then show folders which have parent-id == curParentId or folder-id == curParentId to back folder before
        var streams = document.getElementById('folder-list').getElementsByClassName('stream');
        for(var i = 0; i < streams.length; i++){
            addClass(streams[i], 'hide');
        }
        var folders = document.getElementById('folder-list').getElementsByClassName('folder');
        for(var i = 0; i < folders.length; i++){
            if(folders[i].attributes['parent-id'] !== undefined && folders[i].attributes['parent-id'].value === curParentId){
                removeClass(folders[i], 'hide');
            } else {
                addClass(folders[i], 'hide');
            }
        }
        currentFolderId = curParentId;
        curParentId = '0';
        //close add-folder form
        document.getElementById('add-folder').getElementsByClassName('name')[0].value = '';
        addClass(document.getElementById('add-folder'), 'hide');
        document.getElementById('content').style.marginTop = '90px';
    }, false);
    
    //add event delete folder
    var folder_trashes = document.getElementById('folder-list').getElementsByClassName('delete');
    for(var i = 0; i < folder_trashes.length; i++){
        folder_trashes[i].addEventListener('click', function(e){
            temp = this;
            var pl = new SOAPClientParameters();
            pl.add("folderId", this.parentElement.parentElement.attributes['data-id'].value);
            SOAPClient.invoke("/m/", "deleteFolder", pl, true, deleteFolder_complete);
            e.stopPropagation();
        }, false);
    }
    
    //add event all streams
    document.getElementById('all-folders').addEventListener('click', function(){
        //change folder name on option title
        document.getElementById('folder-name').innerHTML = '<i style="float:left; margin-left:10px;width:30px;">&nbsp; &nbsp;</i>' +
                'FOLDERS<i class="ub ub-plus ub-lg add" style="float: right;width:30px; margin-top:8px; margin-right:10px;"></i>';
        eventShowAddFolderForm();
        //hide add folder button when in streams
        addClass(document.getElementById('option').getElementsByTagName('i')[0], 'hide');
        addClass(document.getElementById('option').getElementsByTagName('i')[1], 'hide');
        //show back folder
        curParentId = '0';
        removeClass(document.getElementById('folder-list').getElementsByClassName('back')[0], 'hide');
        //hide all folders and...
        var folders = document.getElementById('folder-list').getElementsByClassName('folder');
        for(var j = 0; j < folders.length; j++){
            addClass(folders[j], 'hide');
        }
        //show all streams
        var streams = document.getElementById('folder-list').getElementsByClassName('stream');
        for(var j = 0; j < streams.length; j++){
            removeClass(streams[j], 'hide');
        }
        //close add-folder form
        document.getElementById('add-folder').getElementsByClassName('name')[0].value = '';
        addClass(document.getElementById('add-folder'), 'hide');
        document.getElementById('content').style.marginTop = '90px';
    }, false);
    
    //add event show addFolder form
    eventShowAddFolderForm();
}

function eventShowAddFolderForm(){
    //add event show ADD FOLDER form
    document.getElementById('option').getElementsByClassName('add')[0].addEventListener('click', function(){
        var streams = document.getElementById('folder-list').getElementsByClassName('stream');
        var check_addFolder = true;
        for(var i = 0; i < streams.length && check_addFolder; i++){
            if(!window.hasClass(streams[i], 'hide')){
                check_addFolder = false;
            }
        }
        if(check_addFolder){
            removeClass(document.getElementById('add-folder'), 'hide');
            document.getElementById('content').style.marginTop = '50px';
        }
    }, false);
}

function addtaggroup_callback(r){
    if (r !== "null") {
        var pl = new SOAPClientParameters();
        SOAPClient.invoke("/m/", "getGroups", pl, true, getGroups_callback);
        //reset
        addClass(document.getElementById('add-tag-group'), 'hide');
        document.getElementById('content').style.marginTop = '90px';
    }
}

function createTag_complete(r){
    if(r !== 'false'){
        //reset
        addClass(document.getElementById('add-tag-group'), 'hide');
        document.getElementById('content').style.marginTop = '90px';
    }
}

function addfolder_callback(r) {
    if (r === "true") {
        var pl = new SOAPClientParameters();
        SOAPClient.invoke("/m/", "getFolder", pl, true, getfolder_callback);
        //reset
        addClass(document.getElementById('add-folder'), 'hide');
        document.getElementById('content').style.marginTop = '90px';
    }
}

function deleteFolder_complete(r){
    if(r === "succeed"){
        var li = temp.parentNode.parentNode;
        li.parentNode.removeChild(li);
    }
}

var settings_viewport = function(data){
    viewport.innerHTML = data;
    
    //highlight option of settings menu
    var options = viewport.getElementsByTagName('li');
    for(var i = 0; i < options.length; i++){
        if(options[i].attributes['data-type'] !== undefined && options[i].attributes['data-type'].value === params[1]){
            removeClass(viewport.getElementsByClassName('selected')[0], 'selected');
            addClass(options[i], 'selected');
        }
    }
};

var alert_mainview = function(data) {
    controller.innerHTML = data;
};
var date;
var stream_viewport = function(data) {
    viewport.innerHTML = data;
    dateFrom = document.getElementById('datefrom-filter').attributes['value'].value;
    dateTo = document.getElementById('dateto-filter').attributes['value'].value;
    
    //edit link in main-section of viewport
    var main_section = document.getElementById('main-section');
    var engagement_section = main_section.getElementsByClassName('fa-engagement')[0].parentElement;
    var compare_section = main_section.getElementsByClassName('fa-comparison')[0].parentElement;
    var mention_section = main_section.getElementsByClassName('ub-mention')[0].parentElement;
    var metrics_section = main_section.getElementsByClassName('ub-metrics')[0].parentElement;
    engagement_section.attributes['href'].value += streamId;
    compare_section.attributes['href'].value += streamId;
    mention_section.attributes['href'].value += streamId;
    metrics_section.attributes['href'].value += streamId;
    
    addEventMainSection();
    
    //filter default
    document.getElementById('language-filter').value = 2;
    sentiment = document.getElementById('sentiment-filter').value;
    language = document.getElementById('language-filter').value;
    type = document.getElementById('platform-filter').value;
    tag = document.getElementById('tag-filter').value;
};

window.addEvent = function(elem,type,callback) {
    var evt = function(e) {
        e = e || window.event;
        return callback.call(elem,e);
    }, cb = function(e) {return evt(e);};
    if( elem.addEventListener) {
        elem.addEventListener(type,cb,false);
    }
    else if( elem.attachEvent) {
        elem.attachEvent("on"+type,cb);
    }
    return elem;
};
window.findParent = function(child,filter,tagname,root) {
    do {
        if( filter(child) && child.tagName === tagname) return child;
        if( root && child === root) return false;
    } while(child === child.parentNode);
    return false;
};
window.hasClass = function(el,cls) {
    if( !('className' in el)) return;
    return !!el.className.match(new RegExp("\\b"+cls+"\\b"));
};

function addEventAccount(){
    var password_form = document.getElementById('password-account');
    var info_form = document.getElementById('info-account');
    if(document.getElementById('current-password') !== null){
        document.getElementById('change-password').addEventListener('click', function(){
            addClass(this, 'hide');
            removeClass(document.getElementById('back-password'), 'hide');
            password_form.style.height = '240px';
            info_form.style.height = '0px';
        }, false);
        document.getElementById('back-password').addEventListener('click', function(){
            addClass(this, 'hide');
            removeClass(document.getElementById('change-password'), 'hide');
            password_form.style.height = '0px';
            info_form.style.height = '247px';
        }, false);
    }
    document.getElementById('update-account').addEventListener('click', function(){
        if(document.getElementById('current-password') !== null){
            //reset
            document.getElementById('error-account').style.color = 'red';
            document.getElementById('error-account').textContent = '';
            if (window.hasClass(document.getElementById('change-password'), 'hide')) {
                //change password
                oldPassword = document.getElementById('current-password').value;
                newPassword = document.getElementById('new-password').value;
                confirmPassword = document.getElementById('confirm-password').value;
                if (newPassword !== confirmPassword){
                    document.getElementById('error-account').textContent = "Error: Password does not match! Please check it!";
                    removeClass(document.getElementById('error-account'), 'hide');
                } else {
                    var pl = new SOAPClientParameters();
                    pl.add("oldPassword", hex_md5(oldPassword));
                    pl.add("newPassword", hex_md5(newPassword));
                    SOAPClient.invoke("/m/", "changePassword", pl, true, changePassword_callback);
                }
            }else {
                //change info
                firstName = document.getElementById('firstname-account').value;
                lastName = document.getElementById('lastname-account').value;
                if (firstName !== '' && lastName !== '') {
                    var pl = new SOAPClientParameters();
                    name = firstName + ' ' + lastName;
                    pl.add("name", name);
                    SOAPClient.invoke("/m/", "changeName", pl, true, changeName_callback);
                }
                else {
                    document.getElementById('error-account').textContent = "You cannot leave your name empty...";
                    removeClass(document.getElementById('error-account'), 'hide');
                }
            }
        } else {
            oldPassword = 'a2452fba805dad71c12daeb96a0ae40b';
            newPassword = document.getElementById('new-password').value;
            confirmPassword = document.getElementById('confirm-password').value;
            if (newPassword !== confirmPassword){
                document.getElementById('error-account').textContent = "Error: Password does not match! Please check it!";
                removeClass(document.getElementById('error-account'), 'hide');
            } else {
                var pl = new SOAPClientParameters();
                pl.add("oldPassword", oldPassword);
                pl.add("newPassword", hex_md5(newPassword));
                SOAPClient.invoke("/m/", "changePassword", pl, true, changePassword_callback);
            }
        }
    }, false);
}

function changePassword_callback(r){
    if (r === "succeed") {
        window.location = '/logout';
    }
    else {
        document.getElementById('error-account').textContent = "Error: " + r;
        removeClass(document.getElementById('error-account'), 'hide');
    }
}

function changeName_callback(r) {
    if (r === "succeed") {
        document.getElementById('error-account').style.color = 'green';
        document.getElementById('error-account').textContent = "Action performed successfully";
    }
    else {
         document.getElementById('error-account').textContent = "Something wrong :(";
    }
    removeClass(document.getElementById('error-account'), 'hide');
}

function addEventMainMenu(){
    //event of main_menu
    document.getElementById('menu-button').addEventListener('click', function(){
        if(state === 3){
            addClass(document.getElementById("menu-button"), "selected");
            removeClass(document.getElementById("filter-button"), "selected");
        }else {
            if(state === 2){
                addClass(document.getElementById("filter-button"), "selected");
                removeClass(document.getElementById("menu-button"), "selected");
            }
        }

        //menu-button
        addClass(document.getElementById("menu-button"), "selected");
        removeClass(document.getElementById("filter-button"), "selected");
        var content = document.getElementById("content");
        if(state !== 2 && state !== 3)
            curState = state;
        if (!window.hasClass(main_menu, 'show')) {
            curScroll = document.body.scrollTop;
            document.body.scrollTop = 0;
            state = 3;
            addClass(main_menu, "show");
            removeClass(viewport, "show");
            addClass(content, "hide");
            controller.style.height = main_menu.clientHeight + 'px';
            if(curState === 5 || params[0] === 'compare' || params[0] === 'engagement')
                addClass(document.getElementById('option'), 'hide');
        } else {
            removeClass(document.getElementById("menu-button"), "selected");
            removeClass(main_menu, "show");
            removeClass(content, "hide");
            controller.style.height = 'auto';
            document.body.scrollTop = curScroll;
            if(curState === 5 || params[0] === 'compare' || params[0] === 'engagement'){
                removeClass(document.getElementById('option'), 'hide');
            }
            state = curState;
        }
    }, false);
}

function addEventTopBanner(){
    addEventMainMenu();

    //event of stream filter button
    document.getElementById('filter-button').addEventListener('click', function(){
        var content = document.getElementById("content");
        var vp = document.getElementById("view-port");
        if(vp !== null){
            addClass(document.getElementById("filter-button"), "selected");
            removeClass(document.getElementById("menu-button"), "selected");
            if(state !== 2 && state !== 3)
                curState = state;
            if(viewport.className === '') {
                viewport.parentElement.className = "right-nav";
                curScroll = document.body.scrollTop;
                document.body.scrollTop = 0;
                state = 2;
                addClass(viewport, "show");
                removeClass(main_menu, "show");
                addClass(content, 'hide');
                controller.style.height = vp.clientHeight + 'px';
                /*if(curState === 5 || params[0] === 'compare' || params[0] === 'engagement'){
                    addClass(document.getElementById('option'), 'hide');
                }*/
            } else {
                removeClass(document.getElementById("filter-button"), "selected");
                removeClass(content, 'hide');
                removeClass(viewport, "show");
                controller.style.height = 'auto';
                document.body.scrollTop = curScroll;
                if(curState === 5 || params[0] === 'compare' || params[0] === 'engagement'){
                    //removeClass(document.getElementById('option'), 'hide');
                }
                setTimeout(function(){
                    state = curState;
                }, 200);

                //check reloading by filter data
                switch(params[0]){
                    case 'stream':
                        checkLoadStream();
                        break;
                    case 'compare':
                        checkLoadCompare();
                        break;
                    case 'engagement':
                        break;
                }

                if(reload && params[0] === 'stream'){
                    document.getElementById('option').style.marginTop = '0px';
                    document.getElementById('stream-list').innerHTML = '';
                    page = 0;
                    page++;
                    index = 10 * (page - 1);
                    curScroll = document.body.scrollTop = document.getElementById("search").offsetHeight;
                    loadStream(streamId, dateFrom, dateTo, index, language, tag, sentiment, messageActionFilter, type, source);
                }
            }
        }
    });
}

function addEventMainSection(){
    //adding event MAIN SECTION
    var main_section = document.getElementById("main-section");
    var main_sections = main_section.getElementsByTagName('li');
    for(var i = 0; i < main_sections.length; i++){
        main_sections[i].addEventListener('click', function(e){
            if(window.hasClass(this.parentElement,"lv-1")){
                if(!window.hasClass(this,"selected")){
                    //close which selected and its children
                    for(var j = 0; j < main_sections.length; j++){
                        if(window.hasClass(main_sections[j],"selected")){
                            removeClass(main_sections[j], 'selected');
                            var txt = main_sections[j]["innerText" in main_sections[j] ? "innerText" : "textContent"];
                            var sectionType = txt.split('\n')[0].toLowerCase();
                            var child = main_section.getElementsByClassName(sectionType)[0];
                            addClass(child, 'hide');
                            if(sectionType === 'mention'){
                                messageActionFilter = '';
                                reload = true;
                            }
                        }
                    }
                    
                    //select mention-section and show its children
                    addClass(this, 'selected');
                    if(this.attributes.data !== undefined && this.attributes.data.value === 'hasChild'){
                        //show its children if hasChild
                        main_section.parentElement.style.height = '145px';
                        var txt = this["innerText" in this ? "innerText" : "textContent"];
                        var sectionType = txt.split('\n')[0].toLowerCase();
                        var child = main_section.getElementsByClassName(sectionType)[0];
                        removeClass(child, 'hide');
                    }
                    else
                        main_section.parentElement.style.height = 'auto';
                }else{
                    var txt = this["innerText" in this ? "innerText" : "textContent"];
                    var sectionType = txt.split('\n')[0].toLowerCase();
                    var child = main_section.getElementsByClassName(sectionType)[0].getElementsByClassName('selected')[0];
                    if(child !== undefined){
                        removeClass(child, 'selected');
                        switch(sectionType){
                            case 'mention':
                                messageActionFilter = '';
                                reload = true;
                                break;
                        }
                    }
                }
                
                //action of type
                switch(sectionType){
                    case 'mention':
                        removeClass(document.getElementById("filter-button"), "selected");
                        removeClass(document.getElementById("content"), 'hide');
                        removeClass(viewport, "show");
                        controller.style.height = 'auto';
                        document.getElementById('option').style.marginTop = '0px';
                        if(document.getElementById('stream-list') !== null && document.getElementById('stream-list') !== undefined){
                            document.getElementById('stream-list').innerHTML = '';
                            page = 0;
                            page++;
                            index = 10 * (page - 1);
                            curScroll = document.body.scrollTop = document.getElementById("search").offsetHeight;
                            loadStream(streamId, dateFrom, dateTo, index, language, tag, sentiment, messageActionFilter, type, source);
                        }
                        break;
                    case 'metrics':
                        break;
                }
            }else {
                e.stopPropagation();
                //remove which selected
                var brothers = this.parentElement.getElementsByTagName('li');
                for(var j = 0; j < brothers.length; j++){
                    if(window.hasClass(brothers[j], 'selected')){
                        removeClass(brothers[j], 'selected');
                        j = brothers.length;
                    }
                }
                addClass(this, 'selected');
                if(window.hasClass(this.parentElement, 'mention')){
                    messageActionFilter = this["innerText" in this ? "innerText" : "textContent"];
                }else{
                    if(window.hasClass(this.parentElement, 'metrics')){
                        removeClass(document.getElementById("filter-button"), "selected");
                        removeClass(document.getElementById('content'), 'hide');
                        removeClass(viewport, "show");
                        controller.style.height = 'auto';
                        if(curState === 5 || params[0] === 'compare' || params[0] === 'engagement'){
                            removeClass(document.getElementById('option'), 'hide');
                        }
                    }
                }
            }
        }, false);
    }
    
    //settings href of metrics and alert
    for(var i = 0; i < main_sections.length; i++){
        if(main_sections[i].attributes.data !== undefined && main_sections[i].attributes.data.value === "metrics"){
            main_sections[i].attributes.href.value += "/" + window.location.href.split('#')[1].split('/')[1];
            i = main_sections.length;
        }
    }
    //get top source
    var filterdata = {};
    filterdata.dateFrom = dateFrom;
    filterdata.dateTo = dateTo;
    var filter = JSON.stringify(filterdata);
    sendRequest('/ws/topsourcesdata/' + streamId + '/' + filter, function(data) {
        if (data === 'null')
            return;
        var sources = JSON.parse(data);
        var options = '<option value="0">All Sources</option>';
        for (i = 0; i < sources.length; i++) {
            options += '<option value="' + sources[i].source + '">' + sources[i].title + '</option>';
        }
        document.getElementById('sources-filter').innerHTML = options;
    }, process);
}

var folders = document.getElementById('folder').getElementsByTagName('a');
for(var i = 0; i < folders.length; i++){
    folders[i].addEventListener('click', function(){
        if(!window.hasClass(this, 'expanded')){
            if(this.attributes['folderid'] !== undefined){
                //close others
                for(var j = 0; j < folders.length; j++){
                    if(window.hasClass(folders[j], 'expanded')){
                        removeClass(folders[j], 'expanded');
                    }
                }
            }
            if(this.attributes['streamid'] === undefined){
                addClass(this, 'expanded');
            }else{
                removeClass(main_menu, 'show');
                removeClass(document.getElementById("menu-button"), "selected");  
                removeClass(document.getElementById('content'), 'hide');
                if(params[0] === 'stream')
                    document.getElementById('stream-list').innerHTML = '';
                curScroll = document.body.scrollTop = 0;
                controller.style.height = 'auto';
                page = 0;
                reload = true;
                if(streamId !== undefined && this.attributes['streamid'].value === Base64.decode(streamId)){
                    page++;
                    index = 10 * (page - 1);
                    loadStream(streamId, dateFrom, dateTo, index, language, tag, sentiment, messageActionFilter, type, source);
                }
            }
        }else {
            if(this.attributes['streamid'] === undefined){
                removeClass(this, 'expanded');
            }
        }
        controller.style.height = main_menu.clientHeight + 'px';
    }, false);
}

var dashboard = document.getElementById('dashboard').getElementsByTagName('a');
for(var i = 0; i < dashboard.length; i++){
    dashboard[i].addEventListener('click', function(){
        removeClass(main_menu, 'show');
        removeClass(document.getElementById('content'), 'hide');
        removeClass(document.getElementById("menu-button"), "selected");
        controller.style.height = 'auto';
    }, false);
}

var stream_mainview = function(data) {
    controller.innerHTML = data;
    addEventTopBanner();
    addEventStreamButton();
    addEventSearchInStream();
    page++;
    streamId = window.location.href.split('#')[1].split('/')[1];
    index = 10 * (page - 1);
    dateFrom = document.getElementById('stream-list').attributes['data-dateFrom'].value;
    dateTo = document.getElementById('stream-list').attributes['data-dateTo'].value;
    loadStream(streamId, dateFrom, dateTo, index, language, tag, sentiment, messageActionFilter, type, source);
};

function loadMoreThreadsEffect(){
    var load_more = document.getElementsByClassName("load-more")[0];
    load_more.innerHTML = '<h5>Loading more threads...</h5>';
    load_more.style.height = '25px';
    document.getElementById('stream-list').style.marginBottom = '25px';
}

function stopLoadMoreEffect(){
    document.getElementsByClassName("load-more")[0].style.height = '0px';
    document.getElementById('stream-list').style.marginBottom = '0px';
}

function loadMoreRepliesEffect(){
    var load_more = document.getElementsByClassName("load-more")[0];
    load_more.innerHTML = '<h5>Loading more replies...</h5>';
    load_more.style.height = '25px';
    document.getElementById('stream-list').style.marginBottom = '25px';
}

function addEventStreamButton() {
    //clearIcon-button
    document.getElementById('clearIcon').addEventListener('click', function(){
        if(this.className === 'fa fa-clear'){
            this.className = 'fa fa-clear hide';
            document.getElementById('doSearchInStream').value = '';
            searchInStream('');
            removeClass(document.getElementsByClassName("loading")[0], 'hide');
            stopLoadMoreEffect();
            state = 1;
            noMoreMessage = false;
        }
    }, false);
    
    //back-button
    document.getElementById('back-button').addEventListener('click', function(){
        var headers = document.getElementsByClassName('mention-head');
        //reset
        for(var i = 0; i < headers.length; i++){
            var ul = headers[i].parentElement.getElementsByTagName('ul')[0];
            if(ul.className === 'mention-content hide'){
                headers[i].parentElement.className = 'stream';
            }else {
                var content = headers[i].parentElement.getElementsByClassName('content')[0];
                var temp = content.attributes['text'].value;
                content.attributes['text'].value = content.innerHTML;
                content.innerHTML = temp;
                content.className = 'content';
                headers[i].className = 'mention-head';
                ul.className = 'mention-content hide';
                addClass(headers[i].getElementsByClassName('tag-bar')[0], 'hide');
                ul.innerHTML = headers[i].attributes['replies'].value;
            }
        }
        addClass(document.getElementById('social-button').getElementsByTagName('ul')[0], 'hide');
        addClass(document.getElementById('options-button').getElementsByTagName('ul')[0], 'hide');
        document.getElementById('doSearchInStream').value = '';
        searchInStream('');
        document.getElementById('header').attributes['threadid'].value = '';
        document.getElementById('header').attributes['messageid'].value = '';
        removeClass(document.getElementById('search').parentElement, 'hide');
        var options = document.getElementById('options-button').getElementsByTagName('li');
        for(var i = 0; i < options.length; i++){
            if(document.getElementById(options[i].attributes['data'].value) !== null)
                if(!window.hasClass(document.getElementById(options[i].attributes['data'].value), 'hide')){
                    addClass(document.getElementById(options[i].attributes['data'].value), 'hide');
                    i = options.length;
                }
        }
        stopLoadMoreEffect();
        document.getElementById('option').style.marginTop = '0px';
        pause = true;
        addClass(document.getElementById('content'), 'hide');
        removeClass(document.getElementById('loading'), 'hide');
        setTimeout(function(){
            removeClass(document.getElementById('content'), 'hide');
            addClass(document.getElementById('loading'), 'hide');
            document.body.scrollTop = curScroll;
            pause = false;
        }, 200);
        state = 1;
        noMoreMessage = false;
    }, false);
    
    //click event on options-button
    document.getElementById('options-button').addEventListener('click', function(){
        if(window.hasClass(this.getElementsByTagName('ul')[0], 'hide')){
            removeClass(this.getElementsByTagName('ul')[0], 'hide');
            addClass(document.getElementById('social-button').getElementsByTagName('ul')[0], 'hide');
            
            //close current form
            var social = document.getElementById('social-button').getElementsByTagName('li');
            for(var i = 0; i < social.length; i++){
                if(document.getElementById(social[i].attributes['data'].value) !== null)
                    if(!window.hasClass(document.getElementById(social[i].attributes['data'].value), 'hide')){
                        addClass(document.getElementById(social[i].attributes['data'].value), 'hide');
                        removeClass(document.getElementById('search').parentElement, 'hide');
                        return;
                    }
            }
            var options = document.getElementById('options-button').getElementsByTagName('li');
            for(var i = 0; i < options.length; i++){
                if(document.getElementById(options[i].attributes['data'].value) !== null)
                    if(!window.hasClass(document.getElementById(options[i].attributes['data'].value), 'hide')){
                        addClass(document.getElementById(options[i].attributes['data'].value), 'hide');
                        removeClass(document.getElementById('search').parentElement, 'hide');
                        return;
                    }
            }
        }else{
            addClass(this.getElementsByTagName('ul')[0], 'hide');
        }
    }, false);
    
    //child li of options-button
    var options = document.getElementById('options-button').getElementsByTagName('li');
    for(var i = 0; i < options.length; i++){
        options[i].addEventListener('click', function(e){
            var type = this.attributes['data'].value;
            if(type === 'tags'){
                e.stopPropagation();
            }else {
                for(var j = 0; j < options.length; j++){
                    if(document.getElementById(options[j].attributes['data'].value) !== null)
                        if(!window.hasClass(document.getElementById(options[j].attributes['data'].value), 'hide')){
                            addClass(document.getElementById(options[j].attributes['data'].value), 'hide');
                            j = options.length;
                        }
                }
                var form = document.getElementById(type);
                if(form !== null){
                    document.body.scrollTop = 0;
                    removeClass(form, 'hide');
                    addClass(document.getElementById('search').parentElement, 'hide');
                    //reset value
                    var selects = form.getElementsByTagName('select');
                    for (var i = 0; i < selects.length; i++) {
                        selects[i].value = 1;
                    }
                    var inputs = form.getElementsByTagName('input');
                    for (var i = 0; i < inputs.length; i++) {
                        inputs[i].value = '';
                    }
                    var textareas = form.getElementsByTagName('textarea');
                    for (var i = 0; i < textareas.length; i++) {
                        textareas[i].value = '';
                    }
                }
            }
        }, false);
    }
    
    //cancel-button of options
    var cancel_button = document.getElementById('header').getElementsByClassName('cancel');
    for(var i = 0; i < cancel_button.length; i++){
        cancel_button[i].addEventListener('click', function(){
            addClass(this.parentElement.parentElement.parentElement, 'hide');
            removeClass(document.getElementById('search').parentElement, 'hide');
            
            //reset
            switch(this.attributes['dataType'].value){
                case 'send-sms':
                    var sendSMS_form = document.getElementById('send-sms');
                    sendSMS_form.getElementsByTagName('input')[0].value = '';
                    sendSMS_form.getElementsByTagName('textarea')[0].value = '';
                    break;
                case 'add-task':
                    var addTask_form = document.getElementById('add-task');
                    addTask_form.getElementsByTagName('select')[0].value = 1;
                    addTask_form.getElementsByTagName('select')[1].value = 1;
                    addTask_form.getElementsByTagName('input')[0].value = '';
                    addTask_form.getElementsByTagName('textarea')[0].value = '';
                    break;
                case 'reply':
                    var reply_form = document.getElementById('reply');
                    reply_form.getElementsByTagName('textarea')[0].value = '';
                    break;
                case 'facebook':
                    var shareFacebook_form = document.getElementById('reply');
                    shareFacebook_form.getElementsByTagName('textarea')[0].value = '';
                    break;
            }
        }, false);
    }
    
    //submit of options
    var submit_button = document.getElementById('header').getElementsByClassName('submit');
    for(var i = 0; i < submit_button.length; i++){
        submit_button[i].addEventListener('click', function(){
            var type = this.attributes['dataType'].value;
            var pl = new SOAPClientParameters();
            switch(type){
                case 'send-sms':
                    var alert = document.getElementById(type).getElementsByTagName('p')[1];
                    var sendTo = this.parentElement.getElementsByTagName('input')[0].value;
                    var message = this.parentElement.getElementsByTagName('textarea')[0].value;
                    if(sendTo !== '' && message !== ''){
                        pl.add("phoneNumber", sendTo);
                        pl.add("message", message);
                        alert.style.display = 'none';
                        SOAPClient.invoke("/m/", "sendSMS", pl, true, function(r) {
                            var timeout = setTimeout(function() {
                                alert.style.display = '';
                            }, 500);
                        });
                        
                        //reset
                        removeClass(document.getElementById('search').parentElement, 'hide');
                        addClass(document.getElementById(type), 'hide');
                        this.parentElement.getElementsByTagName('input')[0].value = '';
                        this.parentElement.getElementsByTagName('textarea')[0].value = '';
                    }
                    break;
                case 'add-task':
                    var department = this.parentElement.getElementsByTagName('input')[0].value;
                    var description = this.parentElement.getElementsByTagName('textarea')[0].value;
                    if(department !== ''){
                        var assignedTo = this.parentElement.getElementsByTagName('select')[0].value;
                        var taskType = this.parentElement.getElementsByTagName('select')[1].value;
                        var messageId = document.getElementById('header').attributes['messageid'].value;
                        var streamId = document.getElementById('header').attributes['streamid'].value;
                        var curLink = document.getElementsByClassName('mention-head selected')[0].getElementsByClassName('title')[0].attributes['href'].value;
                        var currentPost = document.getElementsByClassName('mention-head selected')[0].getElementsByClassName('content selected')[0].attributes['text'].value;
                        currentPost = currentPost.replace('<span class="readmore-threedot">...</span>', '');
                        pl.add("userId", currentUserId);
                        pl.add("taskType", taskType);
                        pl.add("taskDescription", description);
                        pl.add("assignedTo", assignedTo);
                        pl.add("messageId", messageId);
                        pl.add("streamId", streamId);
                        pl.add("post", '<a href="' + curLink + '" target="_blank">' + currentPost + '</a>');
                        pl.add("department", department);
                        SOAPClient.invoke("/m/", "addTask", pl, true, addTask_callback);
                        
                        //reset
                        removeClass(document.getElementById('search').parentElement, 'hide');
                        addClass(document.getElementById(type), 'hide');
                        this.parentElement.getElementsByTagName('select')[0].value = 1;
                        this.parentElement.getElementsByTagName('select')[1].value = 1;
                        this.parentElement.getElementsByTagName('input')[0].value = '';
                        this.parentElement.getElementsByTagName('textarea')[0].value = '';
                    }
                    break;
                case 'reply':
                    break;
                case 'facebook':
                    var messageContent = this.parentElement.getElementsByTagName('textarea')[0].value;
                    var shareMessageId = document.getElementById('header').attributes['messageid'].value;
                    var shareStreamId = document.getElementById('header').attributes['streamid'].value;
                    var messageLink = document.getElementsByClassName('mention-head selected')[0].getElementsByClassName('title')[0].attributes['href'].value;
                    if(messageContent !== ''){
                        pl.add("messageId", shareMessageId);
                        pl.add("streamId", shareStreamId);
                        pl.add("message", messageContent);
                        pl.add("link", messageLink);
                        SOAPClient.invoke("/m/", "postFacebookStatus", pl, true, shareFacebook_callback);
                    }
                    
                    //reset
                    removeClass(document.getElementById('search').parentElement, 'hide');
                    addClass(document.getElementById(type), 'hide');
                    this.parentElement.getElementsByTagName('textarea')[0].value = '';
                    break;
            }
        }, false);
    }
    
    //social-button
    document.getElementById('social-button').addEventListener('click', function(){
        if(window.hasClass(this.getElementsByTagName('ul')[0], 'hide')){
            removeClass(this.getElementsByTagName('ul')[0], 'hide');
            addClass(document.getElementById('options-button').getElementsByTagName('ul')[0], 'hide');
            
            //close current form
            var social = document.getElementById('social-button').getElementsByTagName('li');
            for(var i = 0; i < social.length; i++){
                if(document.getElementById(social[i].attributes['data'].value) !== null)
                    if(!window.hasClass(document.getElementById(social[i].attributes['data'].value), 'hide')){
                        addClass(document.getElementById(social[i].attributes['data'].value), 'hide');
                        removeClass(document.getElementById('search').parentElement, 'hide');
                        i = social.length;
                    }
            }
            var options = document.getElementById('options-button').getElementsByTagName('li');
            for(var i = 0; i < options.length; i++){
                if(document.getElementById(options[i].attributes['data'].value) !== null)
                    if(!window.hasClass(document.getElementById(options[i].attributes['data'].value), 'hide')){
                        addClass(document.getElementById(options[i].attributes['data'].value), 'hide');
                        removeClass(document.getElementById('search').parentElement, 'hide');
                        i = options.length;
                    }
            }
        }else{
            addClass(this.getElementsByTagName('ul')[0], 'hide');
        }
    }, false);
    
    //child li of social-button
    var social = document.getElementById('social-button').getElementsByTagName('li');
    for(var i = 0; i < social.length; i++){
        social[i].addEventListener('click', function(e){
            var type = this.attributes['data'].value;
            for(var j = 0; j < social.length; j++){
                if(document.getElementById(social[j].attributes['data'].value) !== null)
                    if(!window.hasClass(document.getElementById(social[j].attributes['data'].value), 'hide')){
                        addClass(document.getElementById(social[j].attributes['data'].value), 'hide');
                        j = options.length;
                    }
            }
            var form = document.getElementById(type);
            if(form !== null){
                document.body.scrollTop = 0;
                removeClass(form, 'hide');
                addClass(document.getElementById('search').parentElement, 'hide');
            }
        }, false);
    }
    
    function shareFacebook_callback(r){

    }
    
    function addTask_callback(r){

    }
    //select of tags
    document.getElementById('tags-option').getElementsByTagName('select')[0].addEventListener('change', function(){
        if(this.value !== 0){
            var tag_bar = document.getElementById('stream-list').getElementsByClassName('selected')[0].getElementsByClassName('tag-bar')[0];
            var tag_zone = tag_bar.getElementsByClassName('tag-zone')[0];
            var tags = tag_bar.getElementsByClassName('tag');
            var tagId = this.value;
            var streamId = document.getElementById('header').attributes['streamid'].value;
            var messageId = document.getElementById('header').attributes['messageid'].value;

            //create tagNode
            var tag = document.createElement('div');
            tag.setAttribute('class', 'tag new');
            var namediv = document.createElement('div');
            namediv.setAttribute('class', 'name');
            namediv.textContent = '#' + this.options[this.selectedIndex].text;
            tag.appendChild(namediv);
            var del = document.createElement('div');
            del.setAttribute('class', 'del');
            del.textContent = 'x';
            tag.appendChild(del);

            //delete event of Tag
            tag.getElementsByTagName('div')[1].addEventListener('click', function(){
                var pl = new SOAPClientParameters();
                pl.add('tagId', tagId);
                pl.add('streamId', streamId);
                pl.add('messageId', messageId);
                SOAPClient.invoke('/m/', 'removeTag', pl, true, function() {
                    tag.parentNode.removeChild(tag);
                    tags = tag_bar.getElementsByClassName('tag');
                    var tags_width = 0;
                    for(var i = 0; i < tags.length; i++){
                        tags_width += tags[i].clientWidth + 5;
                    }
                    if(tags_width + 32 <= tag_zone.clientWidth) {
                        addClass(tag_zone.getElementsByClassName('threedot')[0], 'hide');
                        removeClass(tag_zone, 'expanded');
                    }
                    if(tags.length < 2){
                        addClass(tag_bar, 'hide');
                    }
                });
            }, false);

            //show tag-bar
            if(window.hasClass(tag_bar, 'hide')){
                removeClass(tag_bar, 'hide');
            }

            //add Tag
            tag_zone.appendChild(tag);
            var pl = new SOAPClientParameters();
            pl.add("messageId", messageId);
            pl.add("tagId", tagId);
            pl.add("streamId", streamId);
            SOAPClient.invoke("/m/", "addTag", pl, true, null);

            //show expanded
            var tags_width = 0;
            for(var i = 0; i < tags.length; i++){
                tags_width += tags[i].clientWidth + 5;
            }
            if(tags_width + 32 > tag_zone.clientWidth){
                removeClass(tag_zone.getElementsByClassName('threedot')[0], 'hide');
            }
            removeClass(tag_zone.getElementsByClassName('new')[0], 'new');

            //effect fix error with Safari browser
            temp = this.options[this.selectedIndex].text;
            this.options[this.selectedIndex].text = 'Tags';
            selector = this;
            setTimeout(function(){
                selector.options[selector.selectedIndex].text = temp;
                selector.value = '0';
                selector.selectedIndex = 0;
            }, 100);
        }
    },false);
}

var loadstream_callback = function(data) {
    //load more stream
    if(data === 'Your query has no result! Try again!' ){
        if(state !== 4){
            document.getElementById('stream-list').innerHTML = data;
        }
        noMoreMessage = true;
        reload = true;
    }else {
        noMoreMessage = false;
    }

    //get stream-list
    if(!noMoreMessage){
        var currentData = parseURL(document.getElementById('stream-list').innerHTML);
        if(reload){
            reload = false;
            document.getElementById('stream-list').innerHTML = parseURL(data);
            curScroll = document.body.scrollTop = document.getElementById("search").offsetHeight;
        }else {
            var currentTop = document.body.scrollTop;
            document.getElementById('stream-list').innerHTML = currentData + parseURL(data);
            curScroll = document.body.scrollTop = currentTop + document.getElementById("search").offsetHeight;
        }
    }
    
    if(state !== 4){
        //reset
        messageActionFilter = '';
        reload = false;
        pause = false;
        state = 1;
    }
    if(scroll){
        stopLoadMoreEffect();
        scroll = false;
    }
    //load more stream for search
    if(state === 4 && !noMoreMessage){
        searchInStream(document.getElementById('doSearchInStream').value);
    }else {
        stopLoadMoreEffect();
    }
    addClass(document.getElementsByClassName('loading')[0], 'hide');
    addEventMentionHead();
};

var process = function process(re) {

};

function loadStream(streamId, dateFrom, dateTo, index, language, tag, sentiment, messageActionFilter, type, source) {
    var url = "/loadStream/" + streamId + "/" + dateFrom + "/" + dateTo + '/' + index + '/50/' + language + "/" + tag + "/" + sentiment + messageActionFilter + '/' + type + '/' + source;
    if(state !== 4)
        removeClass(document.getElementsByClassName("loading")[0], 'hide');
    StreamReq = sendRequest(url, loadstream_callback, process);
}

function loadReplies(streamId, threadId, index, length, show) {
    var pl = new SOAPClientParameters();
    pl.add('threadId', threadId);
    pl.add('streamId', streamId);
    pl.add('dateFrom', dateFrom);
    pl.add('dateTo', dateTo);
    pl.add('index', index);
    pl.add('length', length);
    SOAPClient.invoke('/m', 'getReplies', pl, true, getRepliesComplete);
}

function getRepliesComplete(r){
    if(r !== 'Your query has no result! Try again!'){
        if(!noMoreMessage){
            data = JSON.parse(r);
            if(data !== null) {
                var ul = document.getElementsByClassName('mention-head selected')[0].parentElement.getElementsByTagName('ul')[0];
                for(var i = 0; i < data.items.length; i++){
                    var item = data.items[i];
                    var li = '<li class="buzz buzz-comment">' +
                                '<div class="comment-detail">' +
                                    '<span class="name">' + item.author + ': </span>' + item.text +
                                '</div>' +
                                '<div class="info">' +
                                    '<span class="social">' +
                                        '<img src="Images/like.png" alt=""><p>' + item.likes + '</p> &nbsp;' +
                                    '</span>' +
                                    '<p class="date-time">' + item.time + '</p>' +
                                '</div>' +
                            '</li>';
                    ul.innerHTML += li;
                }
            }
        }
        noMoreMessage = false;
    }else{
        noMoreMessage = true;
    }
    pause = false;
    stopLoadMoreEffect();
}

document.addEventListener("scroll", scroll, false);
var noMoreMessage = false;
var pause = false;
var scroll = false;
function scroll() {
    if (!noMoreMessage && !pause && state === 1 && params[0] === 'stream'){
        if (document.body.scrollTop > document.body.scrollHeight - window.innerHeight - 400) {
            pause = true;
            loadMoreThreadsEffect();
            page++;
            index = 10 * (page - 1);
            loadStream(streamId, dateFrom, dateTo, index, language, tag, sentiment, messageActionFilter, type, source);
        }
    } else if(!noMoreMessage && !pause && state === 4){
            if (document.body.scrollTop > document.body.scrollHeight - window.innerHeight - 400) {
                loadMoreThreadsEffect();
                scroll = true;
                searchInStream(document.getElementById('doSearchInStream').value);
            }
        } else {
            if(!noMoreMessage && !pause && state === 5 && params[0] === 'stream'){
                if (document.body.scrollTop > document.body.scrollHeight - window.innerHeight - 800) {
                    pause = true;
                    loadMoreRepliesEffect();
                    var threadId = document.getElementById('header').attributes['threadid'].value;
                    var index = document.getElementsByClassName('mention-head selected')[0].parentElement.getElementsByTagName('ul')[0].children.length + 1;
                    var length = 5;
                    loadReplies(streamId, threadId, index, length, false);
                }
            }
        }
};

function sendRequest(url, callback, process) {
    function getXMLHttpRequest() {
        if (window.XMLHttpRequest) {
            return new window.XMLHttpRequest;
        } else {
            try {
                return new ActiveXObject("MSXML2.XMLHTTP");
            } catch (ex) {
                return null;
            }
        }
    }
    var oReq = getXMLHttpRequest();
    function handler() {
        if (oReq.readyState === 4 /* complete */) {
            if (oReq.status === 200) {
                callback(oReq.responseText);
            }
        }
    }

    if (oReq !== null) {
        oReq.open("GET", url, true);
        oReq.onreadystatechange = handler;
        oReq.onprogress = progress;
        oReq.send();
        return oReq;
    } else {
        window.alert("AJAX (XMLHTTP) not supported.");
    }

    function progress() {
        process(oReq);
    }
}

/*
 * Search in stream
 */
var timerSearchInStream = undefined;
function addEventSearchInStream() {
    document.getElementById('doSearchInStream').addEventListener('keyup', function() {
        if (this.value !== '') {
            document.getElementById('clearIcon').className = 'fa fa-clear';
            state = 4;
            addClass(document.getElementsByClassName("loading")[0], 'hide');
        }
        else {
            document.getElementById('clearIcon').className = 'fa fa-clear hide';
            state = 1;
            noMoreMessage = false;
        }

        timerSearchInStream = setTimeout(function() {
            if(document.getElementById('doSearchInStream').value !== ' ')
                searchInStream(document.getElementById('doSearchInStream').value);
        }, 1000);
    }, false);
}

function searchInStream(keyword) {
    var streams = document.getElementsByClassName('stream');
    var count = 0;
    //reset
    if (keyword === '') {
        for(var i = 0; i < streams.length; i++){
            var title = streams[i].getElementsByClassName('title')[0];
            title.innerHTML = title.attributes['text'].value;
            var sources = streams[i].getElementsByClassName('source')[0];
            sources.innerHTML = sources.attributes['text'].value;
            var author = streams[i].getElementsByClassName('author')[0];
            author.innerHTML = author.attributes['text'].value;
            var content = streams[i].getElementsByClassName('content')[0];
            content.innerHTML = content.attributes['text'].value;
            streams[i].className = 'stream';
        }
        return;
    }
    
    for(var i = 0; i < streams.length; i++){
        if(streams[i].className !== 'stream hide'){
            
            //reset before searching
            var title = streams[i].getElementsByClassName('title')[0];
            title.innerHTML = title.attributes['text'].value;
            var sources = streams[i].getElementsByClassName('source')[0];
            sources.innerHTML = sources.attributes['text'].value;
            var author = streams[i].getElementsByClassName('author')[0];
            author.innerHTML = author.attributes['text'].value;
            var content = streams[i].getElementsByClassName('content')[0];
            content.innerHTML = content.attributes['text'].value;

            var hasKeyWord = false;
            var re = new RegExp('(' + keyword + ')(?=[^>]*(<|$))', "gi");

            //search in title
            var titleText = title.innerHTML;
            if (titleText.search(re) !== -1) {
                titleText = titleText.replace(re, '<span class="highlight">$1</span>');
                title.innerHTML = titleText;
                hasKeyWord = true;
            }

            //search in author
            var authorText = author.innerHTML;
            if (authorText.search(re) !== -1) {
                authorText = authorText.replace(re, '<span class="highlight">$1</span>');
                author.innerHTML = authorText;
                hasKeyWord = true;
            }

            //search in source
            var sourceText = sources.innerHTML;
            if (sourceText.search(re) !== -1) {
                sourceText = sourceText.replace(re, '<span class="highlight">$1</span>');
                sources.innerHTML = sourceText;
                hasKeyWord = true;
            }

            //search all text in lead
            var contentText = content.innerHTML;
            if (contentText.search(re) !== -1) {
                contentText = contentText.replace(re, '<span class="highlight">$1</span>');
                content.innerHTML = contentText;
                hasKeyWord = true;
            }

            if(!hasKeyWord){
                streams[i].className = 'stream hide';
            }else {
                count++;
            }
        }
    }
    if(!scroll){
        if(count < 10 && !noMoreMessage){
            loadMoreThreadsEffect();
            page++;
            index = 10 * (page - 1);
            loadStream(streamId, dateFrom, dateTo, index, language, tag, sentiment, messageActionFilter, type, source);
        }else {
            stopLoadMoreEffect();
        }
    } else {
        loadMoreThreadsEffect();
        page++;
        index = 10 * (page - 1);
        loadStream(streamId, dateFrom, dateTo, index, language, tag, sentiment, messageActionFilter, type, source);
    }
    /*//search all replies
    replies = $(this).find('.main-reply-content p');
    var match = false;
    if (replies.length > 0) {
        replies.each(function() {
            var replyContent = $(this).find('.main-reply-content');
            replyContent.html(replyContent.attr('text'));
            var replyText = $(this).html();
            if (replyText.search(re) !== -1) {
                replyText = replyText.replace(re, '<span class="highlight">$1</span>');
                $(this).html(replyText);
                $(this).parents('.mention-top-bar').show();
                match = true;
                if ($(this).find('.readmore-content.hide').html() != undefined)
                    if ($(this).find('.readmore-content.hide').html().search(re) !== -1) {
                        if (!matchTitle && !matchAuthor && !matchSource)
                            $(this).find('.readmore.spanshow:not(.hide)').addClass('highlight');
                    }
            }
            else {
                if (!matchAuthor && !matchSource)
                    $(this).parents('.mention-top-bar').hide();
            }
            $(this).addClass('searched');
        });
    }
    if ((!match && !textMatch) && !matchTitle && !matchAuthor && !matchSource) {
        $(this).hide();
    }*/
}

function addEventMentionHead() {
    //event of mention header
    var headers = document.getElementsByClassName('mention-head');
    for(var i = 0; i < headers.length; i++){
        headers[i].addEventListener('touchstart', function(){
            //close options menu
            addClass(document.getElementById('options-button').getElementsByTagName('ul')[0], 'hide');
            addClass(document.getElementById('social-button').getElementsByTagName('ul')[0], 'hide');
        }, false);
        headers[i].addEventListener('click', function(){
            //stop loadmore-threads
            if(pause){
                pause = false;
                if(StreamReq !== undefined)
                    StreamReq.abort();
                stopLoadMoreEffect();
            }
            
            var mention_content = this.parentElement.getElementsByTagName('ul')[0];
            if(mention_content.className === 'mention-content hide'){
                curScroll = document.body.scrollTop;
                pause = true;
                selector = this;
                addClass(document.getElementById('content'), 'hide');
                removeClass(document.getElementById('loading'), 'hide');
                setTimeout(function(){
                    removeClass(document.getElementById('content'), 'hide');
                    addClass(document.getElementById('loading'), 'hide');
                    pause = false;
                    setTimeout(function(){
                        selector.style.borderLeftColor = '#fff';
                    }, 1000);
                }, 200);
                document.getElementById('stream-list').style.display = 'none';
                mention_content.className = 'mention-content';
                document.getElementById('option').style.marginTop = '50px';
                addClass(this, 'selected');
                
                //hide others
                for(var j = 0; j < headers.length; j++) {
                    var ul = headers[j].parentElement.getElementsByTagName('ul')[0];
                    if(ul.className === 'mention-content hide'){
                        headers[j].parentElement.className = 'stream hide';
                    }
                }
                
                //settings content of single message
                var content = this.parentElement.getElementsByClassName('content')[0];
                var temp = content.attributes['text'].value;
                content.attributes['text'].value = content.innerHTML;
                content.innerHTML = temp;
                addClass(content, 'selected');
                state = 5;
                document.body.scrollTop = 0;
                document.getElementById('stream-list').style.display = '';
                document.getElementById('header').attributes['threadid'].value = this.parentElement.attributes['threadid'].value;  
                document.getElementById('header').attributes['messageid'].value = this.parentElement.attributes['messageid'].value;            
                
                //save replies of single message before expanding
                this.attributes['replies'].value = mention_content.innerHTML;
                
                //settings tag_bar
                var tag_bar = this.getElementsByClassName('tag-bar')[0];
                var tag_zone = tag_bar.getElementsByClassName('tag-zone')[0];
                var tags = tag_bar.getElementsByClassName('tag');
                if(tags.length > 1){
                    removeClass(tag_bar, 'hide');
                    var tags_width = 0;
                    for(var i = 0; i < tags.length; i++){
                        tags_width += tags[i].clientWidth + 5;
                    }
                    if(tags_width + 32 > tag_zone.clientWidth){
                        removeClass(tag_zone.getElementsByClassName('threedot')[0], 'hide');
                    }
                }

                //expand tag-bar
                this.getElementsByClassName('tag-zone')[0].getElementsByClassName('threedot')[0].addEventListener('click', function(){
                    if(!window.hasClass(this.parentElement, 'expanded')){
                        addClass(this.parentElement, 'expanded');
                    }
                    else{
                        removeClass(this.parentElement, 'expanded');
                    }
                }, false);
            }
        }, false);
    }
    
    //event of mention content
    var contents = document.getElementsByClassName('mention-content');
    for(var i = 0; i < contents.length; i++){
        contents[i].addEventListener('touchstart', function(){
            //close options menu
            addClass(document.getElementById('options-button').getElementsByTagName('ul')[0], 'hide');
            addClass(document.getElementById('social-button').getElementsByTagName('ul')[0], 'hide');
        }, false);
    }
}

function format(date){
    var dd = date.getDate();
    var mm = date.getMonth()+1; //January is 0!
    var yyyy = date.getFullYear();

    if(dd < 10) {
        dd = '0' + dd;
    } 

    if(mm < 10) {
        mm = '0' + mm;
    } 
    return dd + '-' + mm + '-' + yyyy;
}

function checkLoadCompare(){
    var datefrom = format(new Date(document.getElementById('datefrom-filter').value));
    if(datefrom !== dateFrom && datefrom !== 'NaN-NaN-NaN'){
        dateFrom = datefrom;
        reload = true;
    }
    var dateto = format(new Date(document.getElementById('dateto-filter').value));
    if(dateto !== dateTo &&  dateto !== 'NaN-NaN-NaN'){
        dateTo = dateto;
        reload = true;
    }
    var sentiment_filter = document.getElementById('sentiment-filter');
    if(sentiment_filter.value !== sentiment){
        sentiment = sentiment_filter.value;
        reload = true;
    }
    var language_filter = document.getElementById('language-filter');
    if(language_filter.value !== language){
        language = language_filter.value;
        reload = true;
    }
    var platform_filter = document.getElementById('platform-filter');
    if(platform_filter.value !== type){
        type = platform_filter.value;
        reload = true;
    }
    var tag_filter = document.getElementById('tag-filter');
    if(tag_filter.value !== tag){
        tag = tag_filter.value;
        reload = true;
    }
}

function checkLoadStream(){
    var datefrom = format(new Date(document.getElementById('datefrom-filter').value));
    if(datefrom !== dateFrom && datefrom !== 'NaN-NaN-NaN'){
        dateFrom = datefrom;
        reload = true;
    }
    var dateto = format(new Date(document.getElementById('dateto-filter').value));
    if(dateto !== dateTo &&  dateto !== 'NaN-NaN-NaN'){
        dateTo = dateto;
        reload = true;
    }
    var sentiment_filter = document.getElementById('sentiment-filter');
    if(sentiment_filter.value !== sentiment){
        sentiment = sentiment_filter.value;
        reload = true;
    }
    var language_filter = document.getElementById('language-filter');
    if(language_filter.value !== language){
        language = language_filter.value;
        reload = true;
    }
    var platform_filter = document.getElementById('platform-filter');
    if(platform_filter.value !== type){
        type = platform_filter.value;
        reload = true;
    }
    var tag_filter = document.getElementById('tag-filter');
    if(tag_filter.value !== tag){
        tag = tag_filter.value;
        reload = true;
    }
    var sources_filter = document.getElementById('sources-filter');
    if(sources_filter.value !== source){
        source = sources_filter.value;
        reload = true;
    }
    if(messageActionFilter !== ''){
        messageActionFilter = '?filter=' + messageActionFilter;
        reload = true;
    }
}

var __urlRegex = /\((\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;\(\)]*[-A-Z0-9+&@#\/%=~_|])(?=[^>]*(<|$))\)/ig;
var __imgRegex = /\.(?:jpe?g|gif|png)$/i;
function parseURL($string) {
    var exp = __urlRegex;
    return $string.replace(exp, function(match) {
        match = match.substring(1, match.length - 1);
        __imgRegex.lastIndex = 0;
        if (__imgRegex.test(match)) {
            match = match.replace(/&amp;/g, '&');
            if (match.indexOf('&url=') !== -1) {
                match = unescape(match.split('&url=')[1]);
            }
            if (match.indexOf('img.youtube.com') === -1)
                return '<img src="' + match + '" class="thumb" />';
            else
                return match;
        }
        else {
            return '<a class="parsed-link hide" href="' + match + '" target="_blank">' + match + '</a>';
        }
    }
    );
}

function createQuery(query) {
    andMark = '';
    streamQuery = '';
    if (query['all']) {
        keywords = query['all'].split(',');
        sQuery = "";
        for (i = 0; i < keywords.length; i++) {
            keywords[i] = keywords[i].trim();
            if (keywords[i].length !== 0) {
                if (keywords[i].indexOf('-') !== -1 || keywords[i].indexOf(' ') !== -1)
                    sQuery += ' "' + keywords[i] + '" &';
                else
                    sQuery += ' ' + keywords[i] + ' &';
            }
        }
        if (sQuery.substring(sQuery.length - 1) === '&')
            sQuery = sQuery.substring(0, sQuery.length - 1);
        streamQuery = ' (' + sQuery + ') ';
        andMark = '& ';
    }
    if (query['none']) {
        keywords = query['none'].split(',');
        sQuery = "";
        for (i = 0; i < keywords.length; i++) {
            keywords[i] = keywords[i].trim();
            if (keywords[i].length !== 0)
                if (keywords[i].indexOf('-') !== -1 || keywords[i].indexOf(' ') !== -1)
                    sQuery += ' "' + keywords[i] + '" &';
                else
                    sQuery += ' ' + keywords[i] + ' &';
        }
        if (sQuery.substring(sQuery.length - 1) === '&')
            sQuery = andMark + '- (' + sQuery.substring(0, sQuery.length - 1) + ') ';
        streamQuery += sQuery;
        andMark = '& ';
    }
    if (query['any']) {
        keywords = query['any'].split(',');
        sQuery = "";
        for (i = 0; i < keywords.length; i++) {
            keywords[i] = keywords[i].trim();
            if (keywords[i].length !== 0)
                if (keywords[i].indexOf('-') !== -1 || keywords[i].indexOf(' ') !== -1)
                    sQuery += ' "' + keywords[i] + '" |';
                else
                    sQuery += ' ' + keywords[i] + ' |';
        }
        if (sQuery.substring(sQuery.length - 1) === '|')
            sQuery = sQuery.substring(0, sQuery.length - 1);
        streamQuery += andMark + ' \n( ' + sQuery + ' ) ';
        andMark = '& ';
    }
    return streamQuery;
}

remove_item = function(arr,value){
    for(b in arr ){
        if(arr[b] === value){
            arr.splice(b,1);
            break;
        }
    }
    return arr;
};


